How can i make a text box readonly
when a button is clicked using JavaScript? I have tried different scripts like:
document.getElementById("text").readonly="on";
but since readonly is a Boolean i don't think it works.
Would i use document.getElementById
or something else? Can i make all of the text-boxes in a form readonly
using one script or would i need a separate script for each text-box? Could this be done using CSS?
Thank you!
document.getElementById("text").disabled=true;
document.getElementById("text").readonly='readonly';
Javascript doesn't use on/off, it generally uses true/false. Some properties such as "checked" and "disabled" are literal switches, as above.
If you want to work on groups of inputs you generally use class names, apply the same class to those you want to affect.
You can do this in plain JavaScript, but you will have to loop through the values:
var fields = document.getElementsByClassName('something');
for(var x=0;x<fields.length;x++) {
fields[x].setAttribute('readonly','readonly');
}
Moving to use jQuery has many benefits since it can all be done in one compact line:
$('.something').attr('readonly','readonly');
Assuming you're not using text
as the ID, and you have more than one input
of type 'text', you could use this
var inputBoxes = document.querySelectorAll("input[type='text']");
for (i = 0; i < inputBoxes.length; i++)
{
inputBoxes[i].disabled=true;
}
As noted by SimonSimCity
When you set the property disabled to true, it's not available for interaction anymore! You won't get it when submitting the form and click-events aren't triggered. This is the difference to setting readonly to true. All interesting browsers support both properties. See also: developer.mozilla.org/en-US/docs/Web/HTML/Element/…
In this case, use inputBoxes[i].readOnly=true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.