Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Disabled Attribute on Input Based on Checkbox in jQuery [duplicate]

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.

like image 468
cchiera Avatar asked Dec 07 '12 04:12

cchiera


2 Answers

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)
});
like image 165
Adil Avatar answered Nov 10 '22 03:11

Adil


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

like image 45
Adam Rackis Avatar answered Nov 10 '22 01:11

Adam Rackis