tags:

views:

65

answers:

3

Hi,

I have a checkbox and if I tick it I want a textfield to become enabled (disabled as default) and when I untick the the checkbox I want it to become disabled again.

I saw here http://stackoverflow.com/questions/1160238/jquery-checkboxes how I caan toggle a CSS class and here http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_disable.2Fenable_a_form_element.3F how I can switch between enabled and disabled with two buttons. But how do I toggle a textfields disabled/enabled status by tick/untick a checkbox?

Thanks in advance.

+2  A: 

You can attach the change handler on the checkbox, and enable/disable the text field with its checked property.

$('#theCheckbox').change(function() {
    $('#theTextfield').attr('disabled', this.checked);
}

(Example: http://jsbin.com/oludu3/2)

KennyTM
A: 
$(':checkbox').click(function(){
   $('input:text').attr('disabled',!this.checked)
});

crazy demo

Reigel
I think you want the change handler, which will fire even if the user clicks a label associated with the checkbox.
Abhijit Rao
http://jsfiddle.net/FArMm/1/ updated example from Reigel.
Tim
@Rao - if the it's label you're worrying, check [crazy demo 2](http://jsfiddle.net/FArMm/2/)
Reigel
Thank you for that, is there just an easy way to delete the text in the textboxes that becomes disabled and untick the checkboxes that becomes disabled?
Martin
A: 

Here's a page that does what you're looking for - it's pretty minimal but shows what you need

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
        <script>
            $(document).ready(function () {
                $("#testcheckbox").change(function () { 
                    $("#testtextfield").attr("disabled", $(this).attr("checked"));
                });
            });
        </script>
    </head>
    <body>
        <input type="checkbox" id="testcheckbox" />
        <input type="text" id="testtextfield" />
    </body>
</html>
SamStephens