Search code examples
javascriptjquerycheckboxjquery-eventsverification

Optimize jQuery small script for checkboxes


I made a small verification script which is supposed to act like this: I have 4 checkboxes, one has a particular way of action, the id of this checkbox is chx0

  • If I checked the chx0 checkbox then it released all the others checked checkboxes

  • If I checked one of all the others checkboxes then it released the chx0 one

Here is my code:

<script type="text/javascript"> 
    
    $(document).ready(function() {
        $('#chx0').click(function() { // click on the chx0 checkbox
           
            if ($('#chx0').attr('checked')) {
                
                $('#chx1').attr('checked', false);
                $('#chx2').attr('checked', false);
                $('#chx3').attr('checked', false);
            }
        });
    
        $('#chx1').click(function() {// click on the chx1 checkbox
           
            if ($('#chx1').attr('checked')) {
                $('#chx0').attr('checked', false);
            }
        });
    
        $('#chx2').click(function() { // click on the chx2 checkbox
           
            if ($('#chx2').attr('checked')) {
                $('#chx0').attr('checked', false);
            }
        });
    
        $('#chx3').click(function() { // click on the chx3 checkbox
           
            if ($('#chx3').attr('checked')) {
                $('#chx0').attr('checked', false);
            }
        });

    });
    
</script> 

This code is working pretty well it just to get more good practice!


Solution

  • I'd put a class on each checkbox

    <input type="checkbox" name="chx0" id="chx0" class="checkbox-group singleton">
    <label for="chx0">Check me out!</label>
    <input type="checkbox" name="chx1" id="chx1" class="checkbox-group">
    <label for="chx1">Check us out!</label>
    <input type="checkbox" name="chx2" id="chx2" class="checkbox-group">
    <label for="chx2">Check them out!</label>
    

    Then with your jQuery you can do

    $('input.checkbox-group').each( function() {
        $(this).click( function() {
            if ( $(this).hasClass('singleton') ) {
                $('input.checkbox-group:checked').removeAttr('checked');
            } else {
                $('input.checkbox-group.singleton').removeAttr('checked');
            }
        };   
    });
    

    Untested, but I think something like that should work. I can't remember if it's better to use the change event rather than click.