JQuery to disable checkbox if another is checked

12,550

Solution 1

You need to wrap the second chunk of code in a change event:

$('#noneAboveCheck').change(function () {
    $('#noneAbove').toggle(this.checked);
}).change();

$('#incarcerated, #support').change(function () {
    if ($(this).attr("checked")) {
        $('#noneAboveCheck').attr('disabled', true);
    } else {
        $('#noneAboveCheck').attr('disabled', false);
    }
});

jsFiddle example

Solution 2

$('#noneAboveCheck').change(function () {
    $('#noneAbove').toggle(this.checked);
}).change();

$('#incarcerated, #support').change(function () {
    if ($(this).is(":checked")) {
        $('#noneAboveCheck').attr('disabled', true);
    } else {
        $('#noneAboveCheck').attr('disabled', false);
    }
});

Demo:

http://jsfiddle.net/vy6ce/

Share:
12,550
Mr Man
Author by

Mr Man

Updated on June 05, 2022

Comments

  • Mr Man
    Mr Man almost 2 years

    I have one checkbox that shows a div if the user checks it. That div contains 2 other checkboxes. If one of those two checkboxes are checked, I want to disable the first checkbox. Some hmtl:

            <p><input id="noneAboveCheck" type="checkbox" />None of the above</p>
            <div id="noneAbove" class="hidden">
              <p><input id="incarcerated" type="checkbox" /></p>
              <p><input id="support" type="checkbox" />Blah Blah</p>
            </div>
    

    And here my jQuery, the toggle for the div works, but not the disabling. The alert was there for testing and it doesnt show either, so I assume my first line is incorrect:

        $('#noneAboveCheck').change(function () {                
          $('#noneAbove').toggle(this.checked);
        }).change();
    
        if ($('#incarcerated, #support').attr("checked")) {
          alert("hello");
          $('#noneAboveCheck').attr('disabled', true);
        } else {
          $('#noneAboveCheck').attr('disabled', false);
        }
    

    One last thing, I am (unfortunately) still using jQuery 1.4, so I dont think I can use .prop(). Thanks for all the help.