Javascript 如何在javascript中设置文本框的只读属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10832587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set readonly property of a textbox in javascript
提问by James Allardice
i have a textbox whose property i need to set as readonly... how to set that? I tried
我有一个文本框,我需要将其属性设置为只读...如何设置?我试过
document.getElementbyid("txtbox").readonly=true;
document.getElementbyid("txtbox").disable=true;
document.getElementbyid("txtbox").setattribute("readonly","readonly");
all these are not working for me. Disable is working but that is passing the control values as null to the database...again that is a problem for me..
所有这些都不适合我。禁用正在工作,但将控制值作为 null 传递给数据库......这对我来说又是一个问题..
回答by Gaurav Agrawal
You can set an ASP.NET textbox readonly through javascript. Here is how:
您可以通过 javascript 将 ASP.NET 文本框设置为只读。方法如下:
<script type="text/javascript">
function setReadOnly(){
var textbox = document.getElementById("TextBox1");
textbox.readOnly = "readonly";//readOnly is cese-sensitive
}
<body onload=" setReadOnly ()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
Hope it'll help you.
希望它会帮助你。
回答by Joel Etherton
The proper way is:
正确的方法是:
document.getElementById("txtbox").setAttribute("readonly", "true");
Or for the jQuery enthusiasts:
或者对于 jQuery 爱好者:
$("#txtbox").attr("readonly", true);
回答by James Allardice
You have numerous issues with the code in your question. The very first example would work if you had got the names of the properties right:
您的问题中的代码有很多问题。如果您的属性名称正确,第一个示例将起作用:
document.getElementById("txtbox").readOnly = true;
Notice the uppercase letters (getElementById
instead of getElementbyid
and readOnly
instead of readonly
).
注意大写字母(getElementById
而不是getElementbyid
和readOnly
而不是readonly
)。
Here's a working exampleof the above.
这是上述的一个工作示例。
As for your 2nd attempt, the property is disabled
, not disable
. And your 3rd attempt, the method is setAttribute
, not setattribute
. As you can see, JavaScript is case sensitive!
至于您的第二次尝试,该属性是disabled
,而不是disable
。而您的第三次尝试,方法是setAttribute
,而不是setattribute
。如您所见,JavaScript 区分大小写!
回答by Shakeel Latif
<script type="text/javascript">
function loading() {
var input_text = document.getElementById("text");
input_text.setAttribute("readOnly", true);
}
Works for me well....... use camelcase with property....... readOnly not as readonly.....
对我来说效果很好.......使用带有属性的驼峰......只读而不是只读......