Also available at

Also available at my website http://tosh.me/ and on Twitter @toshafanasiev

Wednesday 3 November 2010

Controlling Text Input Form Submission

The content of this post is not really ground-breaking stuff but it's the kind of thing I can see myself referring back to and it may be of use to someone else.
I recently implemented an incremental search box on a web application and wanted to control what effect the <ENTER> key had on the form's behaviour. The application is built so that it will work if JavaScript is disabled - the user simply enters a search term and clicks search ( or presses <ENTER> ) to get a list of matches; the client side script supplements this by serving up results as the user types ( fairly standard behaviour ).
As well as handling individual keystrokes I wanted to launch the top search term on <ENTER>. In order to achieve this I had to disable the browser's default behaviour of submitting the form when <ENTER> is pressed in a single line text input.
Below is the neatest solution I could find that worked in all ( major ) browsers ( detail omitted ):
var searchBox
  = document.getElementById( 'searchBox' );

// ....

// use content of search box to refine results
searchBox.onkeyup = function( e ) {
  e = e || window.event; // ensure event obj
  
  if ( e.keyCode == 13/*RETURN*/ ) {
    // use topmost search result
  }
  else {
    // update results using searchBox.value
  }
}

// prevent form submission when <ENTER> is pressed
searchBox.onkeypress = function( e ) {
  e = e || window.event; // ensure event obj

  return e.keyCode != 13/*ENTER*/;
}

I found that the onkeyup event was the best place to use the input's value and the onkeypress event was the best place to control the form's behaviour - I tried other combinations as well as using the event's cancelBubble property and stopPropagation() method as described here http://www.quirksmode.org/js/introevents.html but in the end only the above actually did what I wanted.

No comments:

Post a Comment