Reputation: 114
After trying multiple examples on StackOverflow to fix my issue, I still can't figure out my problem.
I have 3 checkboxes:
<input id="pets_dog" class="text" type="checkbox" class="pets" name="pets[]" value="pets_dog"> Dogs</input>
<input id="pets_cats" class="text" type="checkbox" class="pets" name="pets[]" value="pets_cats"> Cats</input>
<input id="pets_none" class="text" type="checkbox" class="pets" name="pets[]" value="pets_no"> None</input>
And when "pets_none" is checked, I need the other 2 checkboxes to be unchecked and vice versa. Here is my current jQuery code:
$("#pets_none").change(function() {
if($("#pets_none").attr('checked')) {
$("#pets_cats").removeAttr('checked');
$("#pets_dogs").removeAttr('checked');
}
});
I can't figure out for the life of me why it's not working, and appreciate any help.
Upvotes: 3
Views: 28528
Reputation: 146269
Your html should be
<input id="pets_dog" class="text pets" type="checkbox" name="pets[]" value="pets_dog" /> Dogs
<input id="pets_cats" class="text pets" type="checkbox" name="pets[]" value="pets_cats" /> Cats
<input id="pets_none" class="text pets" type="checkbox" name="pets[]" value="pets_no" /> None
JS
$(function(){
$("#pets_none").on('change', function(e) {
if($(this).is(':checked')) {
$("#pets_dog").attr('checked', false);
$("#pets_cats").attr('checked', false);
}
});
});
Update : You have used class attribute twice, it should be as follows
<input id="pets_dog" type="checkbox" class="pets text" name="pets[]" value="pets_dog" /> Dogs
<input id="pets_cats" type="checkbox" class="pets text" name="pets[]" value="pets_cats" /> Cats
<input id="pets_none" type="checkbox" class="text pets" name="pets[]" value="pets_no" /> None
JS
$(function(){
$(".pets").on('change', function(e) {
var el=$(this);
if(el.is(':checked') && el.attr('id')=='pets_none') {
$(".pets").not(el).attr('checked', false);
}
else if(el.is(':checked') && el.attr('id')!='pets_none')
{
$("#pets_none").attr('checked', false);
}
});
});
Upvotes: 6
Reputation: 144729
You can use the prop
method:
$("#pets_none").change(function() {
if (this.checked) {
$("#pets_cats, #pets_dog").prop('checked', false);
}
});
Upvotes: 4
Reputation: 11
var checked = $(this).find('Enable').text().toLowerCase();
$("#chk__Enable").each(function () {
if (checked == 'true') {
$(this).attr('checked', 'checked');
} else {
$(this).removeAttr('checked');
}
});
Upvotes: 1
Reputation: 943
Use the .prop()
method:
...
$("#pets_cats").prop('checked', false);
$("#pets_dogs").prop('checked', false);
...
And to check whether the #pets_none
is checked, use that method too:
$("#pets_none").prop('checked');
Upvotes: 2