6

This is not a duplicate of How to trigger jQuery change event in code, since that deals with the interaction of jQuery with jQuery event listeners, while this question discusses the interaction of jQuery with native event listeners.

I use addEventListener to bind a change event for an input, but $('#input').val('bbbb').change(); can't trigger the alert, how to trigger addEventListener("change",function) function by JQuery

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>code</title>
</head>

<body>
    <script src="http://o6flfbzth.bkt.clouddn.com/jquery-1.12.0.min.js"></script>

    <input id="input" type="text" value="input" />
    <script type="text/javascript">
        document.getElementById("input").addEventListener("change", function() {
        alert(this.value);
    });
    </script>

    <input type="button" value="change input" onclick="  $('#input').val('bbbb').change();" />
</body>

</html>
Community
  • 1
  • 1
tuzhis
  • 63
  • 1
  • 6

2 Answers2

12

You cannot trigger a native event with jQuery's .trigger('change').

You will need to ceate a native event and dispatch it:

const evt = new Event("HTMLEvents");

And then to fire it:

const el = document.getElementById("input");
el.dispatchEvent(evt);

Deprecated:

You will need to create a native event and dispatch it:

var evt = document.createEvent('HTMLEvents');
evt.initEvent('change', true, true);
//            ^         ^     ^
//            |         |     cancelable
//            |         bubbles
//            type

And then to fire it:

var el = document.getElementById("input");
el.dispatchEvent(evt);
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • evt.initEvent is now deprecated on everything but IE. Use new Event('change') constructor for modern browsers (see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events) – Jono Jun 30 '21 at 04:51
0

Bind the change event using jquery.

$("#input").change(function() {
  alert(this.value);
});

Working snippet :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>code</title>
</head>

<body>
    <script src="http://o6flfbzth.bkt.clouddn.com/jquery-1.12.0.min.js"></script>

    <input id="input" type="text" value="input" />
    <script type="text/javascript">
      $( "#input" ).change(function() {
        alert(this.value);
      });
    </script>

    <input type="button" value="change input" onclick="  $('#input').val('bbbb').change();" />
</body>

</html>
Munawir
  • 3,346
  • 9
  • 33
  • 51