如何使用JavaScript将文本框设为只读 [英] How do you make a text box readonly using JavaScript
问题描述
当使用JavaScript单击按钮时,如何使文本框为 readonly
?我尝试了不同的脚本,例如:
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";
但是由于readonly是布尔值,所以我认为它不起作用.
but since readonly is a Boolean i don't think it works.
我会使用 document.getElementById
还是其他?我可以使用一个脚本以 readonly
的形式制作所有文本框,还是需要为每个文本框使用单独的脚本?可以使用CSS完成此操作吗?
谢谢!
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").readonly='readonly';
Javascript不使用on/off,它通常使用true/false.如上所述,某些属性(例如"checked"和"disabled")是文字开关.
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.
您可以使用普通的JavaScript进行此操作,但是您将不得不遍历以下值:
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');
}
使用jQuery可以带来很多好处,因为它们都可以在紧凑的一行中完成:
Moving to use jQuery has many benefits since it can all be done in one compact line:
$('.something').attr('readonly','readonly');
这篇关于如何使用JavaScript将文本框设为只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!