We can use jQuery to disable an input field on a form. The easiest way to do this is using the jQuery prop() method.
$('input').prop('disabled', true);
Here we can use the prop method on an input field, and change its disabled attribute to true.
The disabled attribute is very similar to the readonly attribute, the main difference is that the value of a field with a disabled attribute will not be sent to the server when the form is submitted. While readonly input will.
An example of using jQuery to enable/disable input on a form
Below we will have a simple form with name and email fields. All the information will be disabled to start, but once you click on the edit button, it will enable all of the input fields to be changed. Since this is just an example, none of the information will actually be saved, but you can see how to allow a user to edit a disabled field.
We will then use jQuery to allow the user to click the edit button, and when that is triggered, it will enable all the disabled fields. When the user is done, clicking the “Done editing” button will then disable all of the fields. We will use the jQuery click() and prop() methods. Here is the code:
$(".button1").click(function(){
$('input').prop('disabled', false);
$(".button1").hide();
$(".button2").css('display','inline-block');
});
$(".button2").click(function(){
$('input').prop('disabled', true);
$(".button1").css('display','inline-block');
$(".button2").hide();
});
The final code and output for this example of how to enable and disable input fields using jQuery is below:
Code Output:
Full Code:
Hopefully this article has been useful in helping you understand how to use jQuery to disable input.