javascript tutorial - [Solved-5 Solutions] Event keypress - javascript - java script - javascript array



Problem:

With jQuery, how do WE find out which key was pressed when WE bind to the keypress event?

$('#searchbox input').bind('keypress', function(e) {});
click below button to copy the code. By JavaScript tutorial team

Solution 1:

Actually this is better:

 var code = e.keyCode || e.which;
 if(code == 13) { //Enter keycode
   //Do something		
 }

click below button to copy the code. By JavaScript tutorial team

Solution 2:

Try this

$('#searchbox input').bind('keypress', function(e) {
    if(e.keyCode==13){
        // Enter pressed... do anything here...
    }
});

click below button to copy the code. By JavaScript tutorial team

Solution 3:

If we are using jQuery UWE we have translations for common key codes. In ui/ui/ui.core.js :

$.ui.keyCode = { 
    ...
    ENTER: 13, 
    ...
};
click below button to copy the code. By JavaScript tutorial team

There's also some translations in tests/simulate/jquery.simulate.js but WE could not find any in the core JS library. Mind you, WE merely grep'ed the sources. Maybe there is some other way to get rid of these magic numbers. We can also make use of String.charCodeAt and .fromCharCode:

>>> String.charCodeAt('\r') == 13
true
>>> String.fromCharCode(13) == '\r'
true

click below button to copy the code. By JavaScript tutorial team

Solution 4:

... this example prevents form submission (regularly the basic intention when capturing keystroke #13):

$('input#search').keypress(function(e) {
  if (e.which == '13') {
     e.preventDefault();
     doSomethingWith(this.value);
   }
});

click below button to copy the code. By JavaScript tutorial team

Solution 5:

	// in jquery source code...
 if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode)) {
     event.which = event.charCode || event.keyCode;
 }

 // So we have just to use
 $('#searchbox input').bind('keypress', function(e) {
     if (e.which === 13) {
         alert('ENTER WAS PRESSED');
     }
 });

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Event keypress