We can use jQuery to add the readonly attribute to an input field, making it so the user can highlight or copy text from an input field, but not change it. The easiest way to do this is using the jQuery prop() method.

$('input').prop('readonly', true);

Here we can use the prop method on an input field, and change its readonly attribute to true.

The readonly attribute is very similar to the disabled 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 make an input readonly on a form

Below we will have a simple form with name and email fields. All the information will be readonly 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 will see how to use jQuery to turn an input field to readonly.








Edit
Done editing

We will use jQuery to allow the user to click the edit button, and when that is triggered, we will remove all of the readonly attributes using jQuery. When the user is done, clicking the “Done editing” button will then add all of the readonly attributes to the input fields again using jQuery. We will use the jQuery click() and prop() methods. Here is the code:

$(".button1").click(function(){
  $('input').prop('redonly', false);
  $(".button1").hide();
  $(".button2").css('display','inline-block');
});

$(".button2").click(function(){
  $('input').prop('readonly', true);
  $(".button1").css('display','inline-block');
  $(".button2").hide();
});

The final code and output for this example of how to use jQuery to make an input field readonly is below:

Code Output:






Edit
Done editing

Full Code:








Edit
Done editing

Hopefully this article has been useful in helping you understand how to use jQuery to make an input field readonly.

Categorized in:

jQuery,

Last Update: February 26, 2024