How to Add a “Readonly” Attribute to an?

How can I add readonly to a specific <input>? .attr('readonly') does not work.

4

10 Answers

jQuery <1.9

$('#inputId').attr('readonly', true);

jQuery 1.9+

$('#inputId').prop('readonly', true);

Read more about difference between prop and attr

3

Use $.prop()

$("#descrip").prop("readonly",true);

$("#descrip").prop("readonly",false);
3

Readonly is an attribute as defined in html, so treat it like one.

You need to have something like readonly="readonly" in the object you are working with if you want it not to be editable. And if you want it to be editable again you won't have something like readonly='' (this is not standard if I understood correctly). You really need to remove the attribute as a whole.

As such, while using jquery adding it and removing it is what makes sense.

Set something readonly:

$("#someId").attr('readonly', 'readonly');

Remove readonly:

$("#someId").removeAttr('readonly');

This was the only alternative that really worked for me. Hope it helps!

.attr('readonly', 'readonly') should do the trick. Your .attr('readonly') only returns the value, it doesn't set one.

2

I think "disabled" excludes the input from being sent on the POST

3

You can disable the readonly by using the .removeAttr;

$('#descrip').removeAttr('readonly');

For enabling readonly:

$("#descrip").attr("readonly","true");

For disabling readonly

$("#descrip").attr("readonly","");
3

Use the setAttribute property. Note in example that if select 1 apply the readonly attribute on textbox, otherwise remove the attribute readonly.

document.getElementById("box1").onchange = function(){
  if(document.getElementById("box1").value == 1) {
    document.getElementById("codigo").setAttribute("readonly", true);
  } else {
    document.getElementById("codigo").removeAttribute("readonly");
  }
};

<input type="text" name="codigo" id="codigo"/>

<select id="box1">
<option value="0" >0</option>
<option value="1" >1</option>
<option value="2" >2</option>
</select>

Check the code below:

<input id="mail">

<script>

 document.getElementById('mail').readOnly = true; // makes input readonline
 document.getElementById('mail').readOnly = false; // makes input writeable again

</script>

For jQuery version < 1.9:

$('#inputId').attr('disabled', true);

For jQuery version >= 1.9:

$('#inputId').prop('disabled', true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest