How do you make a text box readonly using JavaScript

荒凉一梦 提交于 2019-12-25 02:43:39

问题


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!


回答1:


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');



回答2:


document.getElementById("text").disabled=true;



回答3:


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



来源:https://stackoverflow.com/questions/22414984/how-do-you-make-a-text-box-readonly-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!