Reputation: 57
Say I have three checkboxes if I check the "No Entry" checkbox other checkboxes should be unchecked if they are checked. If I check on other checkboxes when "No Entry" is checked, "No Entry" should be unchecked. I am trying to implement this using Javascript and jQuery.
<input type="checkbox" class="otherCheckboxes" id="checkbox1" value="1" /> 1
<input type="checkbox" class="otherCheckboxes" id="checkbox2" value="2" /> 2
<input type="checkbox" id="checkbox3" value="No Entry" /> No Entry
I have tried this but it's not functioning according to the above requirement.
$('#checkbox3').click(function() {
if ($(this).is(':checked')) {
$('.otherCheckboxes').attr('checked', false);
}
Upvotes: 0
Views: 358
Reputation: 9614
I would do it this way:
var otherCheckboxes = $('.otherCheckboxes');
var noEntry = $('#checkbox3');
otherCheckboxes.on('change', function(e) {
if( $(this).is(':checked') ) {
noEntry.prop('checked', false);
};
}).trigger('change');
noEntry.on('change', function(e) {
if( noEntry.is(':checked') ) {
otherCheckboxes.prop('checked', false);
};
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<label for="checkbox1"><input type="checkbox" class="otherCheckboxes" id="checkbox1" value="1" /> 1</label>
</p>
<p>
<label for="checkbox2"><input type="checkbox" class="otherCheckboxes" id="checkbox2" value="2" /> 2</label>
</p>
<p>
<label for="checkbox3"><input type="checkbox" id="checkbox3" value="No Entry" /> No Entry</label>
</p>
Also on JSFiddle.
Upvotes: 2
Reputation: 1969
Try this :)
$('input:checkbox').on('click change',function() {
if ($(this).prop('checked')) { //if ($(this).is(':checked')) { will do too
if ($(this).hasClass('otherCheckboxes')) {
$('#checkbox3').prop('checked',false);
} else {
$(this).siblings().prop('checked',false);
}
}
});
Or:
$('input:checkbox').on('click change',function() {
if ($(this).is(':checked')) {
var uncheck = $(this).hasClass('otherCheckboxes')?$('#checkbox3'):$(this).siblings();
uncheck.prop('checked',false);
}
});
Upvotes: 0
Reputation: 6783
$('#checkbox3').change(function() {
if (this.checked) {
$('.otherCheckboxes').each(function(){
this.checked = false;
}
}
Upvotes: 2