Reputation: 4093
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);
}
});
Upvotes: 2
Views: 240
Reputation: 121
Because your code is wrong. .on() event want container of the elements.
So your HTML code should look like this:
<div id="chkContainer">
<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" />
</div>
and JAVASCRIPT function like this:
$('#chkContainer').on('click', 'input:checkbox', function() {
if ( $(this).is(':checked') ) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).attr("checked", false);
$(this).attr("checked", true);
} else {
$(this).attr("checked", false);
}
});
This is an example for you: http://jsfiddle.net/5xDzv/1/
Upvotes: 1
Reputation: 33661
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.
Upvotes: 3
Reputation: 92903
Use .prop('checked',true)
instead of .attr
.
Also, if ($(this).attr("checked") === true)
can be shortened to simply
if ($(this).prop("checked")) {
Upvotes: 7