Victor Santos
Victor Santos

Reputation: 350

jQuery enabling/disabling checkbox

jsFiddle: http://jsfiddle.net/KUcrm/

I have this code:

HTML

<input id="Check1" type="checkbox" name="ckbRG" tabindex="1" checked /><label for="Check1"> Check1</label><br />
<input name="txt1" type="text" maxlength="10" id="txt1" tabindex="2" />
<br /><br /><br />
<input id="Check2" type="checkbox" name="ckbNome" tabindex="3" checked /><label for="Check2"> Check2</label><br />
<input name="txt2" type="text" maxlength="10" id="txt2" tabindex="2" />

jQuery

$("#Check1").click(function() {
    if ($("#Check1").attr("checked")) {
        $("#txt1").removeAttr("disabled");
    } else {
        $("#txt1").attr("disabled", "disabled");
    }
});


$("#Check2").click(function() {
     if ($("#Check2").attr("checked")) {
         $("#txt2").removeAttr("disabled");
     } else {
         $("#txt2").attr("disabled", "disabled");
     }
    $("#Check1").click();
});

By selecting Check2, Check1 should also be selected but apparently the click event on Ckeck1 runs before the Check1 changes state (marked/unmarked). Then when the Check1 is checked txt1 is off and when not selected the txt1 is on.

Upvotes: 0

Views: 576

Answers (2)

Blazemonger
Blazemonger

Reputation: 92893

I think you want:

$("#Check1").click().triggerHandler('click');

http://jsfiddle.net/KUcrm/3/

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174947

You should be using .change instead of click. It will trigger when the checkbox changes.

Upvotes: 1

Related Questions