Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - keydown / keypress /keyup ENTERKEY detection?

Tags:

jquery

Trying to get jQuery to detect enter input, but space and other keys are detected, enter isn't detected. What's wrong below:

$("#entersomething").keyup(function(e) {     alert("up");     var code = (e.keyCode ? e.keyCode : e.which);     if (code==13) {         e.preventDefault();     }      if (code == 32 || code == 13 || code == 188 || code == 186) {         $("#displaysomething").html($(this).val()); });  <input id="entersomething" /> <div id="displaysomething"&gt;&lt;/div&gt; 

http://jsfiddle.net/zeRrv/

like image 753
ina Avatar asked Aug 11 '10 21:08

ina


People also ask

How do you detect a keyboard key is pressed in jQuery?

jQuery | keypress() The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.

What is Keyup and Keydown in jQuery?

jQuery keyup() Method The order of events related to the keyup event: keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.

How do you check if keypress is enter?

In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.

Should I use Keydown or Keyup?

Both are used as per the need of your program and as per the convenience of the user. keyup Fires when the user releases a key, after the default action of that key has been performed. keydown Fires when the user depresses a key.


2 Answers

JavaScript/jQuery

$("#entersomething").keyup(function(e){      var code = e.key; // recommended to use e.key, it's normalized across devices and languages     if(code==="Enter") e.preventDefault();     if(code===" " || code==="Enter" || code===","|| code===";"){         $("#displaysomething").html($(this).val());     } // missing closing if brace }); 

HTML

<input id="entersomething" type="text" /> <!-- put a type attribute in --> <div id="displaysomething"></div> 
like image 117
Russ Cam Avatar answered Sep 29 '22 15:09

Russ Cam


I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.

like image 22
Spencer Mark Avatar answered Sep 29 '22 15:09

Spencer Mark