Javascript 防止在文本字段输入中键入,即使字段未禁用/只读
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35659178/
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
Prevent typing in Text Field Input, Even Though Field is NOT Disabled/Read-Only
提问by gene b.
Can I prevent HTML Text Field input even when my field is NOT Disabled or Read-only? I have this requirement.
即使我的字段未禁用或只读,我也可以阻止 HTML 文本字段输入吗?我有这个要求。
Maybe I can block all inputs via JS or jQuery?
也许我可以通过 JS 或 jQuery 阻止所有输入?
回答by Lal
See this fiddle
看到这个小提琴
You can use jQuery for this.. You can do it as below
您可以为此使用 jQuery .. 您可以按如下方式进行
$('input').keypress(function(e) {
e.preventDefault();
});
OR
或者
you can just return false instead of using preventDefault()
. See the script below
你可以只返回 false 而不是使用preventDefault()
. 看下面的脚本
$('input').keypress(function(e) {
return false
});
See the fiddle
看小提琴
OR
或者
A much simplified version without Javascript would be as below. Just change your HTML as below
一个没有 Javascript 的简化版本如下所示。只需更改您的 HTML 如下
<input type="text" onkeypress="return false;"/>
See the fiddle
看小提琴
回答by DinoMyte
If you wish to make the field complete in-intractable.
如果您希望使该领域变得难以处理。
$('input').focus(function(e) {
$(this).blur();
});
回答by Zakaria Acharki
You could return false on input
event or use .val('')
to reset the field when everytime user try to write something :
您可以在input
事件时返回 false或用于.val('')
在每次用户尝试写入内容时重置该字段:
$('input').input(function(e) {
$(this).val('');
});
Hope this helps.
希望这可以帮助。
$('input').on('input', function(e) {
$(this).val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
回答by Aljo?a
The accepted answer works just fine for me, but I also wanted to include Shift, Esc, and deletekeys. In this case use keydown
instead of keypress
:
接受的答案对我来说很好,但我也想包括Shift、Esc和delete键。在这种情况下使用keydown
代替keypress
:
$('input').keydown(function(e) {
e.preventDefault();
});
Documentation: https://api.jquery.com/keydown/