tuzhis tuzhis - 2 years ago 387
Javascript Question

How to trigger JS native even addEventListener("change",function) by JQuery

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

<meta charset="UTF-8">

<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() {

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


Answer Source

You cannot trigger a native event with jQuery's .trigger('change'). 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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download