Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to uncheck a checkbox in jQuery 1.7?

Tags:

jquery

I'm upgrading from jQuery 1.5.1 -- I've read about the "new" way to "check" checkboxes (in 1.6) using

prop("checked", true);

But what is the correct/preferred way to remove a checkbox?

Both these methods appear to work

$('#someSelector').removeProp("checked");

or

$('#someSelector').prop("checked", false);

Is there a distinction between these methods? Which should I be using?

Thanks

like image 647
rsturim Avatar asked Mar 30 '12 20:03

rsturim


3 Answers

According to http://api.jquery.com/removeprop/ .removeProp should not be used to remove checked. (because it is totally removed and can't be added back again.)

The .removeProp() method removes properties set by the .prop() method.

With some built-in properties of a DOM element or window object, browsers may generate an error if an attempt is made to remove the property. jQuery first assigns the value undefined to the property and ignores any error the browser generates. In general, it is only necessary to remove custom properties that have been set on an object, and not built-in (native) properties.

Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.

like image 138
davepreston Avatar answered Nov 08 '22 13:11

davepreston


To answer your question more precisely:

I would always prefer

$('#someSelector').prop('checked', false);

over

$('#someSelector').removeProp('checked');

because an important difference between attribute and property is in this case, that removing the attribute equals to setting the property (is-checked) to false.

Removing the "checked" property of a checkbox does not make any sense at all, because the checkbox will always be either checked or unchecked. Therefore setting the property to false to uncheck the box is logically consistent, removing the property is not.

like image 35
Niko Avatar answered Nov 08 '22 14:11

Niko


hiya I though out my comment above will be too much text crammed in so writing it here for clarity: (And I agree with @Claudio)

If this does not help let me know I will remove my post cheers! :)

so from here: http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/

[quote] as of 1.6 i reckon...

element Value is something else then it’s property or attribute’s value. When you want to uncheck a checkbox, you want to remove the checked property so use $(“#subscribe:checked”).prop(“checked”, false);

[quote]

jQuery 1.6+

Use the new .prop() function:

$(".myCheckbox").prop("checked", true);

$(".myCheckbox").prop("checked", false);

Setting "checked" for a checkbox with jQuery? hope it helps, you are correct I reckon! cheers!

like image 3
Tats_innit Avatar answered Nov 08 '22 14:11

Tats_innit