简体   繁体   中英

uncheck all check boxes other then one when clicked on a particular checkbox

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);
}
$('#checkbox3').change(function() {
if (this.checked) {
    $('.otherCheckboxes').each(function(){
        this.checked = false;
    }
}

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 .

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);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM