[javascript] How to add a “readonly” attribute to an <input>?

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

This question is related to javascript jquery

The answer is


You can disable the readonly by using the .removeAttr;

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

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

http://jsfiddle.net/baqxz7ym/2/

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>

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


For jQuery version < 1.9:

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

For jQuery version >= 1.9:

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

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>

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.


For enabling readonly:

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

For disabling readonly

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

Use $.prop()

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

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