this code works in jQuery, ver. 1.6
<input type="checkbox" class="radio" value="1" name="sameName" />
<input type="checkbox" class="radio" value="1" name="sameName" />
<input type="checkbox" class="radio" value="1" name="sameName" />
$("input:checkbox").click(function() {
if ($(this).attr("checked") === true) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).attr("checked", false);
$(this).attr("checked", true);
} else {
$(this).attr("checked", false);
}
});
BUT if I change the code using new methods of jQuery 1.7 it wont work? why? thanks for yr time :
$("input:checkbox").on('click', function() {
if ($(this).attr("checked") === true) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).attr("checked", false);
$(this).attr("checked", true);
} else {
$(this).attr("checked", false);
}
});
Use .prop('checked',true) instead of .attr.
http://api.jquery.com/prop
Also, if ($(this).attr("checked") === true) can be shortened to simply
if ($(this).prop("checked")) {
attr returns a string. You should be using .prop to set the checked property for jQuery 1.6+
$("input:checkbox").on('click', function() {
if (this.checked) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).prop("checked", false);
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
From jQuery .prop() docs
The .prop() method should be used to set disabled and checked instead of the .attr() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With