简体   繁体   English

如果使用 jQuery val() 或 JavaScript 更改值,则输入事件不起作用

[英]Input event not working if value is changed with jQuery val() or JavaScript

If I change the value of an input field programmatically, the input and change events are not firing.如果我以编程方式更改输入字段的值,则不会触发inputchange事件。 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.我不想做的事情:我可以遍历我的所有代码,手动在任何地方添加trigger或函数调用,但这不是我想要的。

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.如果有一种方法可以在我的代码中的任何输入更改时自动触发事件,那将节省我很多时间。

Simple solution: 简单方案:

Trigger input after you call val() : 调用val()后触发input

$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> 

Specific solution: 具体方案:

As mentioned you don't want to trigger input manually. 如上所述,您不希望手动触发input This solution triggers the event automatically by overriding val() . 此解决方案通过覆盖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);

See JSFiddle Demo 参见JSFiddle演示

PS PS

Notice this.is('input:text') in the condition. 请注意条件中的this.is('input:text') If you want to trigger the event for more types, add them to the condition. 如果要为更多类型触发事件,请将它们添加到条件中。

There are some ways on how to achieve it. 有一些方法可以实现它。 Here, you can use the levelup HTML's oninput() event that occurs immediately when an element is changed and call the function. 在这里,您可以使用在更改元素时立即发生的oninput() HTML的oninput()事件并调用该函数。

<input id="myinput" type="text" oninput="sample_func()" />
<button id="change">Change value</button>

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

.

var input = $("#myinput");

function sample_func(){
  alert(input.val());
}

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

Or this jQuery, input thing (just related to above example). 或者这个jQuery, input东西(只与上面的例子有关)。

<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>

.

var input = $("#myinput");

input.on("input", function() {
  alert(input.val());
});

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

You can also use javascript setInterval() which constantly runs with a given interval time. 您还可以使用javascript setInterval() ,它在给定的间隔时间内不断运行。 It's only optional and best if you're doing time-related program. 如果您正在进行与时间相关的计划,那么它是唯一可选的。

<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>

.

var input = $("#myinput");

setInterval(function() { ObserveInputValue(input.val()); }, 100);

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

Looks like there's no way, other than using .trigger() . 看起来除了使用.trigger()之外.trigger()

Let's try the same thing using .change() event: 让我们使用.change()事件尝试相同的事情:

 var $input = $("#myinput"); $input.on('change paste keyup', function() { alert($(this).val()); }); $('#change').click(function() { $input.val($input.val() + 'x').trigger("change"); }); 
 <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> 

Or you need to trigger it manually: 或者您需要手动触发它:

$('#change').click(function() {
  $input.val($input.val() + 'x').trigger("input");
});

Snippet 片段

 var $input = $("#myinput"); $input.on('input', function() { alert($(this).val()); }); $('#change').click(function() { $input.val($input.val() + 'x').trigger("input"); }); 
 <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> 

jQuery listeners only work on actual browser events and those aren't thrown when you change something programmatically. jQuery侦听器仅适用于实际的浏览器事件,并且在以编程方式更改某些内容时不会抛出这些事件。

You could create your own miniature jQuery extension to proxy this so that you always trigger the event but only have to do in one modular place, like so: 你可以创建自己的微型jQuery扩展来代理这个,这样你总是可以触发事件但只需要在一个模块化的地方进行,如下所示:

$.fn.changeTextField = function (value) {
  return $(this).val(value).trigger("change");
}

Then, just call your new function whenever you want to update your text field, instead of using jQuery's 'val' function: 然后,只要您想要更新文本字段,而不是使用jQuery的'val'函数,只需调用您的新函数:

$("#myInput").changeTextField("foo");

Here's a version working with a proxy function: 这是一个使用代理功能的版本:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Test stuff</title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
        </head>
        <body>

  <input id="myInput" type="text" />
        <button id="myButton">Change value</button>

        <script type="text/javascript">
            $.fn.changeTextField = function (value) {
             return $(this).val(value).trigger("change");
            }

            $( document ).ready(function() {
                var $input = $("#myInput");

                $input.on("change", function() {
                    alert($input.val());
                });

                $('#myButton').click(function() {
                    $("#myInput").changeTextField("foo");
                });
            });
        </script>
        </body>
    </html>

For reference, this question has really already been answered here: Why does the jquery change event not trigger when I set the value of a select using val()? 作为参考,这个问题在这里已经得到了解答: 为什么当我使用val()设置select的值时,jquery更改事件不会触发?

and here: JQuery detecting Programatic change event 在这里: JQuery检测Programatic变更事件

 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> 

Trigger didn't work for. 触发器不起作用。 Creating an event and dispatching with native JavaScript did the work. 创建一个事件并使用本机JavaScript进行调度完成了这项工作。

Source: https://stackoverflow.com/a/41593131/6825339 资料来源: https//stackoverflow.com/a/41593131/6825339

 <script type="text/javascript">
            $.fn.changeTextField = function (value) {
             return $(this).val(value).dispatchEvent(new Event("input", { bubbles: true });
            }

            $( document ).ready(function() {
                var $input = $("#myInput");

                $input.on("change", function() {
                    alert($input.val());
                });

                $('#myButton').click(function() {
                    $("#myInput").changeTextField("foo");
                });
            });
        </script>

试试这个

$('#input').trigger('change');
$input.val($input.val() + 'x')
$input.trigger('change');

The change event only fire when input blur. 更改事件仅在输入模糊时触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM