making noise since 1977

Internet Explorer onchange on Enter

« | Sat July 5, 2008 | comments and reactions | permanent link | »

This post is more than two years old. It might be still-relevant and maybe even awesome, but it's probably outdated (and likely embarassing!) Proceed with care.

We recently uncovered an interesting browser inconsistency: while pressing Enter in a textbox in most browsers will fire the onchange event, in Internet Explorer it does not. It seems that IE only fires the onchange event when the content of the textbox has changed and the textbox no longer has focus. Unfortunately, the only way to remove focus in IE is to either manually Tab out of the textbox or click elsewhere.

Ordinarily, this would not pose much of a problem, especially considering that the default action when pressing Enter is to submit the form. However, there are many instances where a developer may wish to disable this default form-submitting behavior.

In our case, we were capturing input from a barcode scanner, which uses a new line/carriage return as a message terminator, and we needed this NL/CR to fire the onchange event to trigger some AJAX processing of the data (without submitting the form). The cross-browser solution (which makes IE behave like the other tested browsers) turned out to be fairly simple.

All we needed to do was use a function to detect an Enter/NL/CR and "blur()" the element:

function checkEnter(event)
   var keynum;
   var keychar;
   var enttest;

   if (window.event)
      keynum = event.keyCode;
      if (event.which)
         keynum = event.which;

   keychar = String.fromCharCode(keynum);
   enttest = "r";

   if (enttest == keychar)
      return false;

We simply call the above function using the onkeypress event:

Blur() -ing the element when /r is detected makes IE fire the onchange event for the textbox. Presumably then, in the "otherStuff" function called by the onchange event, you can specify where focus should next be placed.

blog comments powered by Disqus