7

I have a checkbox that is unchecked by default and a disabled input by default.

<label class="checkbox span3"><input type="checkbox"> I am a full-time student.</label>
<input class="inputIcon span3" id="disabledInput" type="text" placeholder="Enter School Name" disabled>

I have full control over the class and id names and the site uses jQuery so can use that or plain javascript if needed.

If a user checks the box, then the "disabled" attribute should be removed from the following input. If the user unchecks it should become disabled again.

Found a several similar questions on StackOverflow but none seem to be this exact use case.

Adam Rackis
  • 81,646
  • 52
  • 262
  • 388
cchiera
  • 2,644
  • 11
  • 36
  • 59

3 Answers3

19

You have to assign id to checkbox to bind the click to particular checkbox,

Live Demo

<input type="checkbox" id="chk">

$("#chk").click(function(){   
    $("#disabledInput").attr('disabled', !this.checked)
});
Adil
  • 143,427
  • 25
  • 201
  • 198
  • This option seems the cleanest. Trying it out now. – cchiera Dec 07 '12 at 04:42
  • noticed function was mispelled, after fixing that, this works perfectly. Thanks! – cchiera Dec 07 '12 at 04:48
  • Thanks @heavymark, so nice of you. – Adil Dec 07 '12 at 04:49
  • One last question. If the input did not have "disabled" by default and I wanted checking the box to add "disabled" and unchecking to remove it (so the opposite of my example above), is there any quick change for that to the code? IF not, no worries! – cchiera Dec 07 '12 at 04:58
  • @heavymark, There is no change in this code whether your input is disabled or enabled by default – Abhilash Dec 07 '12 at 05:17
  • 1
    You may need this, http://jsfiddle.net/rajaadil/vwsvE/2/ – Adil Dec 07 '12 at 05:18
2

First give your checkbox an id

<input id='cbFullTime' type="checkbox">

Then in its click handler, fetch the textbox, and set its disabled property to the inverse of the current value of the checkbox's checked property:

$('#cbFullTime').click(function() { 
    var cbIsChecked = $(this).prop('checked');
    $('#disabledInput').prop('disabled', !cbIsChecked); 
});

Note that, while using attr and removeAttr will work (assuming you're not using exactly jQuery 1.6), using the prop function is a bit simpler, and a bit more correct. For more information, check out this link

Adam Rackis
  • 81,646
  • 52
  • 262
  • 388
1

Try the below

$(".checkbox").find("checkbox").click(function() { 
$('#disabledInput').prop('disabled', $(this).prop('checked')); 
});
Sridhar Narasimhan
  • 2,613
  • 2
  • 15
  • 25