Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable/enable element with checkbox and jQuery?

Tags:

jquery

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 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.

like image 522
Martin Avatar asked Sep 27 '10 07:09

Martin


People also ask

How do I make a checkbox checked and disabled in jQuery?

Syntax: // Select all child input of type checkbox // with class child-checkbox // And add the disabled attribute to them $('. child-checkbox input[type=checkbox]') . attr('disabled', true);

Is checkbox disabled jQuery?

In general, the checkbox disabling in jQuery is defined as disabling the checkbox element which grays out the checkbox element which can either be checked or unchecked when it is disabled by using different methods provided in jQuery such as using a prop() and attr() method and there is also one property which can be ...

How Disable checkbox button is unchecked in jQuery?

$( "#x" ). prop( "checked", false );

How check checkbox is enabled in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);


2 Answers

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

crazy demo

like image 199
Reigel Avatar answered Nov 06 '22 22:11

Reigel


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

like image 39
kennytm Avatar answered Nov 06 '22 22:11

kennytm