将文本框设置为只读在 Javascript 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19182455/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:41:34  来源:igfitidea点击:

Setting textbox to readonly not working in Javascript

javascripttextboxreadonly

提问by Frank Martin

I have tried the following codes to set a textbox property to readonly but none of them is working. Can anyone tell me how to do it?

我尝试了以下代码将文本框属性设置为只读,但它们都不起作用。谁能告诉我怎么做?

document.getElementById("phone_numbers").disabled=true;
document.getElementById("phone_numbers").readonly=true;
document.getElementById("phone_numbers").readOnly=true;
document.getElementById("phone_numbers").readOnly=readOnly;
document.getElementById("phone_numbers").readOnly=readonly;
document.getElementById("phone_numbers").readonly=readonly;
document.getElementById("phone_numbers").readonly=readOnly;
document.getElementById("phone_numbers").setAttribute('readonly', 'readonly');
document.getElementById("phone_numbers").setAttribute("readonly", "true");

EDIT
While I was editing my question to write more detail I realized what the problem was. I made a silly mistake. This was my original HTML code.

编辑
当我编辑我的问题以写出更多细节时,我意识到问题是什么。我犯了一个愚蠢的错误。这是我原来的 HTML 代码。

<input name="phone_numbers">

And I changed it to

我把它改成

<input id="phone_numbers">

And it worked!

它奏效了!

By the way following are the functions that are actually working.

顺便说一下,以下是实际工作的功能。

document.getElementById("phone_numbers").disabled=true;
document.getElementById("phone_numbers").readOnly=true;
document.getElementById("phone_numbers").setAttribute('readonly', 'readonly');
document.getElementById("phone_numbers").setAttribute("readonly", "true");

回答by Bucket

Your third line worked for me: JSFiddle

你的第三行对我有用JSFiddle

HTML

HTML

<input id="phone_numbers" type="textbox"></input>

Javascript

Javascript

document.getElementById("phone_numbers").readOnly=true;

回答by Pavan Kumar

If the textboxis server side, then use document.getElementById("<%= phone_numbers.ClientId %>")to access it.

如果textbox是服务器端,则使用document.getElementById("<%= phone_numbers.ClientId %>")它来访问它。