Thursday, November 15, 2012

Check if Enter Key has been pressed

I keep forgetting the simple way to check if the Enter Key has been pressed while filling out a form. All too often, users assume the presence of default button for the Enter Key next to textboxes that they fill out...

/*
1. Check if Enter Key has been pressed
2. If Enter Key has been pressed, 
   bind click event with a handler to the default button among siblings.
3. Trigger click() event
*/
$('input[type=text]').bind({   
  keypress: function( event ) {
    if( checkIfEnterKeyPressed() ){ //1.Check if Enter Key has been pressed
      var message = 
        'Enter key has been pressed while in ' + $(this).attr('id') + '.';
      $(this).siblings('.defaultButton').bind( //2. Bind click event handler
        'click', 
        { msg: message }, 
        function( event ){
          alert( event.data.msg + '\n' + $(this).val() + ' has been clicked()' );
        }
      ).click(); //3. Trigger click event
    }
  }
});

function checkIfEnterKeyPressed() {  
  var keycode = ( event.keyCode ? event.keyCode : event.which ); 
  return ( keycode == '13' ? true : false );
}




No comments: