Many times you need to Disable or Enable controls with jQuery. Here use the jQuery Prop Method to enable or disable any control.
To disable any control with jQuery pass true as the second argument to the .prop() method.
$("#id").prop("disabled", true)
Similary, to enable any control with jQuery pass false:
$("#id").prop("disabled", false)
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);
});
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);
});
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 addinga 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);
});
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");
DOWNLOAD Codes: