How to use jQuery to Disable & Enable Controls

How to use jQuery to Disable & Enable Controls

Many times you need to Disable or Enable controls with jQuery. Here use the jQuery Prop Method to enable or disable any control.

Syntax of jQuery Disable & Enable Controls

To disable any control with jQuery pass true as the second argument to the .prop() method.

$("#id").prop("disabled",true)

To enable any control with jQuery:

$("#id").prop("disabled",true)

Disable Input on Button Click

There is an input control and a button. On the button click event I will disable the input control.

See the below code:

<input type="text" id="input1" />
<button id="button1">Disable Input</button>
$("#button1").click(function () {
    $("#input1").prop("disabled", true);
});

Enable a Disabled Input Control on Button Click

Here I have a disabled input control which I will enable on the button click.

<input type="text" id="input2" disabled />
<button id="button2">Enable Input</button>
$("#button2").click(function () {
    $("#input2").prop("disabled", false);
});

Keeping the button Disabled till the checkbox is Checked

Sometimes you want to keep the submit button of a form disabled. This is done so that users have to first check the agreed checkbox in order to submit the form.

In the below short form there is an input control for adding name, a checkbox for ‘Agree to our terms’ and a button.

The button remains disabled until the checkbox is check. In this way I can make the user to ‘agree to our terms’ first before he/she can submit the form.

The below jQuery code does this work:

<input type="text" placeholder="your name" />
<input type="checkbox" id="agreeCheckbox" /> Agree to our terms
<button id="button4" disabled>Submit</button>
$("#agreeCheckbox").change(function () {
    if ($(this).is(":checked"))
        $("#button4").prop("disabled", false);
    else
        $("#button4").prop("disabled", true);
});

jQuery :disabled selector

The :disabled selector selects all the disabled controls.

Suppose in my web page I have few controls that are disabled and I want to change their background color to green.

Here I can use the jQuery :disabled selector like this:

$(":disabled").css("background", "#22ea22");

To select only input controls that are disabled use:

$("input:disabled").css("background", "#22ea22");

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.