Reputation: 17049
How can I add readonly
to a specific <input>
? .attr('readonly')
does not work.
Upvotes: 354
Views: 884312
Reputation: 1
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>
Upvotes: -3
Reputation: 21
For jQuery version < 1.9:
$('#inputId').attr('disabled', true);
For jQuery version >= 1.9:
$('#inputId').prop('disabled', true);
Upvotes: -8
Reputation: 1332
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>
Upvotes: 6
Reputation: 827992
jQuery <1.9
$('#inputId').attr('readonly', true);
jQuery 1.9+
$('#inputId').prop('readonly', true);
Read more about difference between prop and attr
Upvotes: 637
Reputation:
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!
Upvotes: 30
Reputation: 8784
Use $.prop()
$("#descrip").prop("readonly",true);
$("#descrip").prop("readonly",false);
Upvotes: 159
Reputation: 121
You can disable the readonly by using the .removeAttr;
$('#descrip').removeAttr('readonly');
Upvotes: 12
Reputation: 417
For enabling readonly:
$("#descrip").attr("readonly","true");
For disabling readonly
$("#descrip").attr("readonly","");
Upvotes: 5
Reputation: 180147
.attr('readonly', 'readonly')
should do the trick. Your .attr('readonly')
only returns the value, it doesn't set one.
Upvotes: 20