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

后端 未结 7 2103
孤城傲影
孤城傲影 2020-12-28 16:12

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

相关标签:
7条回答
  • 2020-12-28 16:34

    Trigger didn't work for. Creating an event and dispatching with native JavaScript did the work.

    Source: 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>
    
    0 讨论(0)
  • 2020-12-28 16:36

    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.

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

    <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. 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');
    });
    
    0 讨论(0)
  • 2020-12-28 16:36

    Looks like there's no way, other than using .trigger().

    Let's try the same thing using .change() event:

    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>

    0 讨论(0)
  • 2020-12-28 16:37

    Simple solution:

    Trigger input after you call 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>

    Specific solution:

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

    See JSFiddle Demo

    PS

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

    0 讨论(0)
  • 2020-12-28 16:43

    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>

    0 讨论(0)
  • 2020-12-28 16:44

    jQuery listeners only work on actual browser events and those aren't thrown when you change something programmatically.

    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:

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

    $("#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()?

    and here: JQuery detecting Programatic change event

    0 讨论(0)
提交回复
热议问题