Javascript 如何阻止在输入文本中写入?

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

How to block writing in input text?

javascript

提问by Luis

I just creating a booking system and I want that the users will choose a date from the calender and it'll show in input text - that I did!

我只是创建了一个预订系统,我希望用户从日历中选择一个日期,它会显示在输入文本中 - 我做到了!

Now I want to block the writing in the input text (just bring to calender writes there when the user choose a date). How do I do it? I guess JavaScript, but how? I dont know JS very wall..

现在我想阻止输入文本中的书写(当用户选择日期时,只需将日历写入那里)。我该怎么做?我猜是 JavaScript,但如何呢?我不知道JS很墙..

Thank you very much!

非常感谢!

采纳答案by Marko

<input type="text" id="someId" disabled="disabled" />

The disabled property will prevent any user input, but you can still write to it via your javascript calendar method.

disabled 属性将阻止任何用户输入,但您仍然可以通过您的 javascript 日历方法写入它。

回答by Sarfraz

Give your element the readonlyattribute, this will disallow users to type anything into it. However, you will still be able to write to add through javascript for example when a date is chosen. Here is an example:

为您的元素提供readonly属性,这将禁止用户在其中输入任何内容。但是,您仍然可以通过 javascript 编写添加内容,例如在选择日期时。下面是一个例子:

<input type="text" id="txt" readonly="readonly">

JavaScript:

JavaScript:

var el = document.getElementById('txt');
el.value = "Testing......";

Working Demo

工作演示

回答by Kenny Aires

For those who wants to prevent typing but not having the disabled style, can try:

对于那些想要阻止打字但没有禁用样式的人,可以尝试:

<input type="text" onkeypress="return false;"/>