如果使用jQuery val()或JavaScript更改值,则输入事件不起作用 [英] Input event not working if value is changed with jQuery val() or JavaScript

查看:537
本文介绍了如果使用jQuery val()或JavaScript更改值,则输入事件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我以编程方式更改输入字段的值,则输入更改事件不会触发。例如,我有这种情况:

If I change the value of an input field programmatically, the input and change events are not firing. For example, I have this scenario:

var $input = $('#myinput');

$input.on('input', function() {
  // Do this when value changes
  alert($input.val());
});

$('#change').click(function() {
  // Change the value
  $input.val($input.val() + 'x');
});

<input id="myinput" type="text" />
<button id="change">Change value</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

问题:当我输入文本字段时触发事件,但是当我按按钮。有没有办法通过某种事件或其他方式实现这一点,而无需手动执行?

The problem: The event is triggered when I type in the textfield, but not when I press the button. Is there a way to achieve this with some kind of event or otherwise without having to do it manually?

我不想做的事情:我可以通过我的所有代码添加一个触发器或函数调用无处不在手动,但这不是我正在寻找。

What I don't want to do: I could go through all my code to add a trigger or function call everywhere manually, but that's not what I'm looking for.

为什么:喜欢这样做是自动的,我有很多输入字段和很多不同的地方,我以编程方式更改这些输入。如果有任何方式在我的代码中的任何地方更改任何输入时,如果有办法自动触发事件,会节省大量时间。

Why: The main reason I would like to do this automatically is that I have a lot of input fields and a lot of different places where I change these inputs programmatically. It would save me a lot of time if there was a way to fire the event automatically when any input is changed anywhere in my code.

推荐答案

简单解决方案:

触发器输入在您调用 val()之后:

$input.trigger("input");

var $input = $("#myinput");

$input.on('input', function() {
  alert($(this).val());
});

$('#change').click(function() {
  // Change the value and trigger input
  $input.val($input.val() + 'x').trigger("input");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input id="myinput" type="text" />
<button id="change">Change value</button>

具体解决方案:

如上所述,您不想手动触发输入。此解决方案通过覆盖 val()自动触发事件。

As mentioned you don't want to trigger input manually. This solution triggers the event automatically by overriding val().

只需将其添加到您的代码中:

Just add this to your code:

(function ($) {
    var originalVal = $.fn.val;
    $.fn.val = function (value) {
        var res = originalVal.apply(this, arguments);

        if (this.is('input:text') && arguments.length >= 1) {
            // this is input type=text setter
            this.trigger("input");
        }

        return res;
    };
})(jQuery);

请参阅 JSFiddle Demo

PS

通知 this.is('input:text')中的条件。如果要触发更多类型的事件,请将其添加到条件。

Notice this.is('input:text') in the condition. If you want to trigger the event for more types, add them to the condition.

这篇关于如果使用jQuery val()或JavaScript更改值,则输入事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆