Javascript 如何防止用户在不禁用字段的情况下输入文本字段?

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

How to prevent user from typing in text field without disabling the field?

javascriptjqueryhtml

提问by Jacob

I tried:

我试过:

$('input').keyup(function() {

   $(this).attr('val', '');

});

but it removes the entered text slightly after a letter is entered. Is there anyway to prevent the user from entering text completely without resorting to disabling the text field?

但它会在输入一个字母后稍微删除输入的文本。无论如何要防止用户完全输入文本而不诉诸禁用文本字段?

回答by Mike Mertsock

A non-Javascript alternative that can be easily overlooked: can you use the readonlyattribute instead of the disabledattribute? It prevents editing the text in the input, but browsers style the input differently (less likely to "grey it out") e.g. <input readonly type="text" ...>

一个很容易被忽视的非 Javascript 替代方案:你可以使用readonly属性而不是disabled属性吗?它可以防止编辑输入中的文本,但浏览器会以不同的方式设置输入的样式(不太可能“变灰”),例如<input readonly type="text" ...>

回答by Art

if you don't want the field to look "disabled" or smth, just use this:

如果您不希望该字段看起来“已禁用”或不正常,请使用以下命令:

onkeydown="return false;"

it's basically the same that greengit and Derek said but a little shorter

基本上和greengit和Derek说的一样,但要短一点

回答by treecoder

$('input').keydown(function(e) {
   e.preventDefault();
   return false;
});

回答by Derek Hunziker

$('input').keypress(function(e) {
    e.preventDefault();
});

回答by Mystical

If you want to prevent the user from adding anything, but provide them with the ability to erase characters:

如果您想阻止用户添加任何内容,但要为他们提供擦除字符的能力:

<input value="CAN'T ADD TO THIS" maxlength="0" />

Setting the maxlengthattribute of an input to "0"makes it so that the user is unable to add content, but still erase content as they wish.

maxlength输入的属性设置为"0"使用户无法添加内容,但仍可以根据需要删除内容



But If you want it to be truly constant and unchangeable:

但是,如果您希望它真正保持不变且不可更改:

<input value="THIS IS READONLY" onkeydown="return false" />

Setting the onkeydownattribute to return falsemakes the input ignore user keypresseson it, thus preventing them from changing or affecting the value.

onkeydown属性设置为return false使输入忽略用户keypresses从而防止他们更改或影响值。

回答by qw3n

One other method that could be used depending on the need $('input').onfocus(function(){this.blur()});I think this is how you would write it. I am not proficient in jquery.

可以根据需要使用的另一种方法$('input').onfocus(function(){this.blur()});我认为这就是您编写它的方式。我不精通jquery。

回答by Biju kalanjoor

Markup

标记

<asp:TextBox ID="txtDateOfBirth" runat="server" onkeydown="javascript:preventInput(event);" onpaste="return false;"
                                TabIndex="1">

Script

脚本

function preventInput(evnt) {
//Checked In IE9,Chrome,FireFox
if (evnt.which != 9) evnt.preventDefault();}

回答by irJvV

I like to add one that also works with dynamic javascript DOM creation like D3 where it is impossible to add:

我喜欢添加一个也适用于动态 javascript DOM 创建的 D3,其中无法添加:

//.attr(function(){if(condition){"readonly"]else{""}) //INCORRECT CODE !

to prevent actions on a HTML input DOM element add readonly to class:

要防止对 HTML 输入 DOM 元素进行操作,请将 readonly 添加到类:

var d = document.getElementById("div1");
d.className += " readonly";

OR in D3:

或在 D3 中:

 .classed("readonly", function(){
   if(condition){return true}else{return false}
 })

AND add to CSS or less:

并添加到 CSS 或更少:

.readonly {
  pointer-events: none;
}

the nice thing about this solution is that you can dynamically turn it on and of in a function so it can be integrated in for example D3 at creation time (not possible with the single "readonly" attribute).

这个解决方案的好处是你可以在一个函数中动态地打开和关闭它,所以它可以在创建时集成到例如 D3 中(单个“只读”属性不可能)。

to remove the element from class:

从类中删除元素:

document.getElementById("MyID").className =
  document.getElementById("MyID").className.replace(/\breadonly\b/,'');

or use Jquery:

或使用 Jquery:

$( "div" ).removeClass( "readonly" )

or toggle the class:

或切换类:

$( "div" ).toggleClass( "readonly", addOrRemove );

Just to be complete, good luck =^)

只是为了完成,祝你好运=^)

回答by anand360

just use onkeydown="return false" to the control tag like shown below, it will not accept values from user.

只需使用 onkeydown="return false" 到如下所示的控制标签,它不会接受来自用户的值。

    <asp:TextBox ID="txtDate" runat="server" AutoPostBack="True"
ontextchanged="txtDate_TextChanged" onkeydown="return false" >
    </asp:TextBox>

回答by JKS

One option is to bind a handler to the inputevent.

一种选择是将处理程序绑定到input事件。

The advantage of this approach is that we don't prevent keyboard behaviors that the user expects (e.g. tab, page up/down, etc.).

这种方法的优点是我们不会阻止用户期望的键盘行为(例如选项卡、向上/向下翻页等)。

Another advantage is that it also handles the case when the input value is changed by pasting text through the context menu.

另一个优点是它还可以处理通过上下文菜单粘贴文本来更改输入值的情况。

This approach works best if you only care about keeping the input empty. If you want to maintain a specific value, you'll have to track that somewhere else (in a data attribute?) since it will not be available when the inputevent is received.

如果您只关心保持输入为空,则此方法效果最佳。如果你想保持一个特定的值,你必须在其他地方(在数据属性中?)跟踪它,因为它在input接收到事件时不可用。

const inputEl = document.querySelector('input');

inputEl.addEventListener('input', (event) => {
  event.target.value = '';
});
<input type="text" />

Tested in Safari 10, Firefox 49, Chrome 54, IE 11.

在 Safari 10、Firefox 49、Chrome 54、IE 11 中测试。