Control third check box based on the state of the first two using jquery

Posted by Moj on Stack Overflow See other posts from Stack Overflow or by Moj
Published on 2010-06-13T00:30:45Z Indexed on 2010/06/13 0:32 UTC
Read the original article Hit count: 526

Filed under:
|

I have three check boxes and need to disable the third if either and/or of the other two are checked. I'm sure there's a easier way than what I have currently. It's turning into what I believe is a mess and I'm hoping that someone with more jquery knowledge can shine the light here.

Here's my simple html form:

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script src="custom.js" type="text/javascript"></script>
</head>
<body>
        <input type="checkbox" class="class" id="1">First
        <input type="checkbox" class="class" id="2">Second
        <input type="checkbox" class="class" id="3">Third
    </body>
</html>

Here's the javascript I'm using with jquery v1.4.2

jQuery(document).ready(function() {
// watches the events of all checkboxes
$(":checkbox").click(function(){
if(
    // if both 1 and 2 are checked we don't want to enable Third until both are unchecked.
    (($('#1:checkbox').attr('checked'))&&($('#2:checkbox').attr('checked')))||
    ((($('#1:checkbox').attr('checked'))&&($('#2:checkbox').attr('checked')))&&($('#3:checkbox').attr('disabled')))||
    ((($('#1:checkbox').attr('checked'))||($('#2:checkbox').attr('checked')))&&($('#3:checkbox').attr('disabled')))
){
    // we don't want to do anything in the above events
} else if( 

    // handles the First check box
    (($('#1:checkbox').attr('checked'))||(!$('#1:checkbox').attr('checked')))||
    // handles the Second check box
    (($('#2:checkbox').attr('checked'))||(!$('#2:checkbox').attr('checked')))

){
// call the disableThird function
disableThird();
}
});

// handles enabling and disabling the Third checkbox
function disableThird(){
    var $checkbox = $('#3:checkbox');
    $checkbox.attr('disabled', !$checkbox.attr('disabled'));
};
});

For some reason checking #3 will disable it's self. I don't understand why.

This works, but one of the requirements is that a non programmer should be able to edit and maintain this. Ideally it'd be great if he could just add new check boxes to the html and it would work. The class for these are define and as far as I know can't be changed. The last check box in the list of check boxes will disable if any of the ones above are selected. Like wise if the last check box is selected, it will disable all the ones above it. I haven't even begun writing and testing that portion as this is quickly becoming too complicated for a non programmer to handle. I myself am more of a PHP coder than a js, let alone jquery, coder. Any help would be greatly appreciated.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about checkboxes