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

前端 未结 4 1692
轮回少年
轮回少年 2021-01-05 14:30

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 w

相关标签:
4条回答
  • 2021-01-05 15:00

    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!

    0 讨论(0)
  • 2021-01-05 15:05

    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.

    0 讨论(0)
  • 2021-01-05 15:07

    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.

    0 讨论(0)
  • 2021-01-05 15:18
    $('#someSelector').removeAttr('checked');
    

    Remove the checked attribute and you should be good to go.

    More info about prop vs attr here. They also mention the checked attribute and call it out specifically as an attribute, not a property.

    http://api.jquery.com/prop/

    0 讨论(0)
提交回复
热议问题