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

Answers 1

  • 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.


Related Articles