简体   繁体   中英

Changing input value inside “input” event handler prevents “change” event firing in Chrome and IE (but not in Firefox)

In the following code I have "input" event handler that changes the value of the input as the user types. I also have "change" event handler to keep track of any changes made to this field. For some reason "change" event doesn't fire in Chrome and IE when the user leaves the field. Why is that and how to make it work in all major browsers?

Also note that it's not acceptable to trigger "change" event manually every time "input" event fires.

EDIT : "change" event seems to fire in Chrome only if transform function does not change the resulting string in any way. So if I type lower case letters and focus out after every character, "change" fires only for indexes 0, 2, 4 ...

Link to fiddle: http://jsfiddle.net/3hqxx2pr/

 function transform(s) { var r = ""; for (var i = 0; i < s.length; i++) { r += i & 1 ? s[i].toUpperCase() : s[i]; } return r; } $(document).ready(function(){ $("#in").on("change", function() { console.log("changed"); // works only in ff }); $("#in").on("input propertychange", function() { $("#in").val(transform($("#in").val())); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <input id="in"/> 

Trigger change yourself

$("#in").val(transform($("#in").val())).change();

or

$("#in").val(transform($("#in").val())).trigger("change");

Based on a edit and restriction you made:

$("#in").on("input propertychange", function() {
    var inp = $(this);
    var orgVal = inp.val();
    var transVal = transform(orgVal);
    if (orgVal !== transVal) {
        inp.val(transVal).trigger("change");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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