简体   繁体   中英

How to fix javascript not working on newer jquery library but working on older version jquery library?

i have this javascript code whhich makes checkbox work as radio

JAVASCRIPT

$(function() {$('input[type=checkbox]').click(function() {
        $('input[type=checkbox]').attr('checked', false);
        $(this).attr('checked', true);
    });
});

HTML

<label title="cat"><input name="" type="checkbox" checked>cat</label>
<label title="dog"><input name="" type="checkbox" >dog</label>
<label title="lion"><input name="" type="checkbox" >lion</label>
<label title="fish"><input name="" type="checkbox" >fish</label>
<label title="turtle"><input name="" type="checkbox" >turtle</label>

Which was working when i was using older jquery library of version 1.8.3 but when i tried to include the newer jquery library of version 1.11.0 , its not working,

how can i fix it ?

here is http://jsfiddle.net/6upmbbf0/

if you change the jquery version on top left to 1.8.3 or lower it works but above 1.8.3 it doesnt.

The correct method to retrieve and update a checkbox's checked state is .prop() . The .attr() simply retrieves or updates the attribute value; it does not necessarily update the underlying state of the input .


jQuery Core 1.9 upgrade guide mentions that behavior is changed, which explains why your code worked in jQuery < version 1.9.

Use not() instead of toggling the checkbox 2 times. If you exclude the checked checkbox in the first place, and uncheck the others, it works better.

$('input[type=checkbox]').not($(this)).prop('checked', false);

fiddle: http://jsfiddle.net/6upmbbf0/3/

edit, added suggestion by Salman A to use prop() instead of attr()

Use 'prop' Instead of 'attr' as

replace code

$(function() {$('input[type=checkbox]').click(function() {
        $('input[type=checkbox]').prop('checked', false);
        $(this).prop('checked', true);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM