Reputation: 2379
I've got the code below
If a checkbox is checked, it should uncheck the other, and then show a div. If the other checkbox is checked, it should uncheck the other and show the div.
it works one way round, but not the other. I can't work out how to make it work both ways.
$('#ssUseDates, #isSearchByDate').click(function() {
if($('#isSearchByDate').attr('checked')) {
$('#ssUseDates').removeAttr('checked');
$('#searchDates').show();
}
else if($('#ssUseDates').attr('checked')) {
$('#isSearchByDate').removeAttr('checked');
$('#searchDates').show();
}
If I check the #ssUseDates box, then check the #isSearchByDate box, it works perfectly, unchecking the #ssUseDates box then showing the div. If I check the #isSearchByDate box, then the #ssUseDates box, it doesn't work, won't let the box check and doesn't uncheck the other.
Thanks for any advice offered.
Upvotes: 0
Views: 772
Reputation: 146310
Give both the same class name and add a ref to the id you want to show try this:
$('.checkClass').change(function() {
if($(this).is(':checked')) {
$('.checkClass').not(this).attr('checked', false).change();
$('#'+$(this).attr('ref')).show();
}
else {
$('#'+$(this).attr('ref')).hide();
}
});
Here is a fiddle: http://jsfiddle.net/maniator/9dvDd/5/
Upvotes: 0
Reputation: 92913
I think the if...else...
in the shared click()
is your problem. Try splitting it up:
http://jsfiddle.net/TG2ne/6/
$(function() {
$('#isSearchByDate').click(function() {
if ($('#isSearchByDate').attr('checked')) {
$('#ssUseDates').removeAttr('checked');
$('#searchDates').show();
}
});
$('#ssUseDates').click(function() {
if ($('#ssUseDates').attr('checked')) {
$('#isSearchByDate').removeAttr('checked');
$('#searchDates').show();
}
});
});
Alternatively (and less attractively), you could test the id of the clicked element as well: http://jsfiddle.net/TG2ne/11/
$(function() {
$('#ssUseDates, #isSearchByDate').click(function() {
if ($(this).attr("id") == "isSearchByDate" && $('#isSearchByDate').attr('checked')) {
$('#ssUseDates').removeAttr('checked');
$('#searchDates').show();
} else if ($(this).attr("id") == "ssUseDates" && $('#ssUseDates').attr('checked')) {
$('#isSearchByDate').removeAttr('checked');
$('#searchDates').show();
}
})
})
Upvotes: 1