Internet Explorer

The Internet Explorer jQuery Change Event Puzzle

While working on a huge user interface development project some time ago, I came across some strange behavior from Internet Explorer that I thought might be worth sharing. In simple terms, it seems the .change jQuery event handler does not work consistently across all browsers, all environments, and all situations.

The user interface code I had written did something along the lines of the following:

$(".container").append("<input id='field_a' type='text' />");
$("#field_a").change(function(){
  // do something
});

Looks pretty straightforward, doesn’t it. It worked in Chrome, Firefox, Internet Explorer (on my work laptop), and even on the version of Chrome installed within Raspbian on a Raspberry Pi. It didn’t work in some cases on laptops used by the client on-site.

I started digging, and eventually found some similar conversations at StackOverflow. I resolved the issue by changing my code to look like this:

$(".container").append("<input id='field_a' type='text' />");
$("#field_a").on("change",function(){
  // do something
});

The only different is the use of on(), rather than change() directly. The interesting thing about this is the jQuery documentation specifically states that change() is shorthand for on(). I beg to differ. Something is different about it – I haven’t had time to look into the source of jQuery yet, but would be interested to find out if anybody else has ever seen this.

Posted by Jonathan Beckett in Notes, 0 comments