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"></div>
http://jsfiddle.net/zeRrv/
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.
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.
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With