Reputation:
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.
Upvotes: 0
Views: 57
Reputation: 272066
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.
Upvotes: 3
Reputation: 58
Use 'prop' Instead of 'attr' as
replace code
$(function() {$('input[type=checkbox]').click(function() {
$('input[type=checkbox]').prop('checked', false);
$(this).prop('checked', true);
});
});
Upvotes: 1
Reputation: 24815
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()
Upvotes: 1