如何使用 jQuery 实现 <input type="text"> 的 onchange?

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

How do I implement onchange of <input type="text"> with jQuery?

jqueryinputonchange

提问by omg

<select>has this API. What about <input>?

<select>有这个API。怎么样<input>

回答by iPadDeveloper2011

As @pimvdb said in his comment,

正如@pimvdb 在评论中所说,

Note that change will only fire when the input element has lost focus. There is also the input event which fires whenever the textbox updates without it needing to lose focus. Unlike key events it also works for pasting/dragging text.

请注意,仅当输入元素失去焦点时才会触发更改。还有一个 input 事件,它会在文本框更新时触发而无需失去焦点。与键事件不同,它也适用于粘贴/拖动文本。

(See documentation.)

(请参阅文档。)

This is so useful, it is worth putting it in an answer. Currently (v1.8*?) there is no .input() convenience fn in jquery, so the way to do it is

这太有用了,值得放在答案中。目前 (v1.8*?) 在 jquery 中没有 .input() 便利 fn,所以这样做的方法是

$('input.myTextInput').on('input',function(e){
 alert('Changed!')
});

回答by Greg

You can use .change()

您可以使用 .change()

$('input[name=myInput]').change(function() { ... });

However, this event will only fire when the selector has lost focus, so you will need to click somewhere else to have this work.

但是,此事件只会在选择器失去焦点时触发,因此您需要单击其他位置才能进行此操作。

If that's not quite right for you, you could use some of the other jQuery eventslike keyup, keydownor keypress- depending on the exact effect you want.

如果这不太适合您,您可以使用其他一些jQuery 事件,例如keyupkeydownkeypress- 取决于您想要的确切效果。

回答by Andrew

I would suggest using the keyup event something like below:

我建议使用 keyup 事件,如下所示:

$('elementName').keyup(function() {
 alert("Key up detected");
});

There are a few ways of achieving the same result so I guess it's down to preference and depends on how you want it to work exactly.

有几种方法可以实现相同的结果,所以我想这取决于偏好,取决于您希望它如何准确工作。

Update: This only works for manual input not copy and paste.

更新:这仅适用于手动输入,不适用于复制和粘贴。

For copy and paste I would recommend the following:

对于复制和粘贴,我建议如下:

$('elementName').on('input',function(e){
 // Code here
});

回答by Mike Gledhill

Here's the code I use:

这是我使用的代码:

$("#tbSearch").on('change keyup paste', function () {
    ApplyFilter();
});

function ApplyFilter() {
    var searchString = $("#tbSearch").val();
    //  ... etc...
}

<input type="text" id="tbSearch" name="tbSearch" />

This works quite nicely, particularly when paired up with a jqGridcontrol. You can just type into a textbox and immediatelyview the results in your jqGrid.

这非常有效,特别是与jqGrid控件配对时。您只需在文本框中键入内容并立即jqGrid.

回答by David Hellsing

There is one and only one reliable way to do this, and it is by pulling the value in an interval and comparing it to a cached value.

一种且只有一种可靠的方法可以做到这一点,它是通过在一个时间间隔内拉取值并将其与缓存值进行比较。

The reason why this is the only way is because there are multiple ways to change an input field using various inputs (keyboard, mouse, paste, browser history, voiceinput etc.) and you can never detect all of them using standard events in a cross-browser environment.

这是唯一方法的原因是因为有多种方法可以使用各种输入(键盘、鼠标、粘贴、浏览器历史记录、语音输入等)来更改输入字段,并且您永远无法使用交叉中的标准事件检测所有这些- 浏览器环境。

Luckily, thanks to the event infrastructure in jQuery, it's quite easy to add your own inputchange event. I did so here:

幸运的是,由于 jQuery 中的事件基础设施,添加您自己的 inputchange 事件非常容易。我在这里这样做:

$.event.special.inputchange = {
    setup: function() {
        var self = this, val;
        $.data(this, 'timer', window.setInterval(function() {
            val = self.value;
            if ( $.data( self, 'cache') != val ) {
                $.data( self, 'cache', val );
                $( self ).trigger( 'inputchange' );
            }
        }, 20));
    },
    teardown: function() {
        window.clearInterval( $.data(this, 'timer') );
    },
    add: function() {
        $.data(this, 'cache', this.value);
    }
};

Use it like: $('input').on('inputchange', function() { console.log(this.value) });

像这样使用它: $('input').on('inputchange', function() { console.log(this.value) });

There is a demo here: http://jsfiddle.net/LGAWY/

这里有一个演示:http: //jsfiddle.net/LGAWY/

If you're scared of multiple intervals, you can bind/unbind this event on focus/blur.

如果您害怕多个间隔,您可以在focus/上绑定/取消绑定此事件blur

回答by Developer

<input id="item123" class="firstName" type="text" value="Hello there" data-someattr="CoolExample" />

$(".firstName").on('change keyup paste', function () {
   var element = $(this);
   console.log(element);
   var dataAttribute = $(element).attr("data-someattr");
   console.log("someattr: " + dataAttribute );
});

I recommend use thiskeyword in order to get access to the entire element so your are able do everything you need with this element.

我建议使用this关键字来访问整个元素,这样你就可以用这个元素做你需要的一切。

回答by Vinith

The following will work even if it is dynamic/Ajax calls.

即使是动态/Ajax 调用,以下内容也将起作用。

Script:

脚本:

jQuery('body').on('keyup','input.addressCls',function(){
  console.log('working');
});

Html,

网址,

<input class="addressCls" type="text" name="address" value="" required/>

I hope this working code will help someone who is trying to access dynamically/Ajax calls...

我希望这个工作代码能帮助那些试图访问动态/Ajax 调用的人......

回答by Phu

$("input").keyup(function () {
    alert("Changed!");
});

回答by Siddhesh Mishra

You could simply work with the id

你可以简单地使用 id

$("#your_id").on("change",function() {
    alert(this.value);
});

回答by Rokan Nashp

You can do this in different ways, keyupis one of them. But i am giving example below with on change.

您可以通过不同的方式执行此操作,keyup就是其中之一。但我在下面给出了变化的例子。

$('input[name="vat_id"]').on('change', function() {
    if($(this).val().length == 0) {
        alert('Input field is empty');
    }
});

NB: input[name="vat_id"]replace with your input IDor name.

注意:input[name="vat_id"]替换为您的输入IDname