When Enter, Backspace, Spacebar keys are pressed - Javascript

When the Enter, Backspace or Spacebar key is pressed, I want to call the Javascript function. Can you please give me suggestion how to make it work with onKeyPress event ?
posted on 11.01.2020 at 12:49
0pnshow more
StorStor
Hi,

To call the specific javascript function, when the enter, backspace or spacebar key is pressed, you can use the solution below. Event onKeyPress doesn't work with backspace key. But you can use onKeyDown event instead of onKeyPress event:



<script>
function keyPressed(keycode) {
if(keycode==13){ alert('Enter key pressed'); }
else if (keycode==8){ alert('Backspace key pressed'); }
else if (keycode==32){ alert('Spacebar key pressed'); }
}
</script>

<input type="text" name="idnumber" onKeyDown="javascript: var key = event.keyCode || event.charCode || event.which ; keyPressed(key); " />



In Javascript events the key codes are:
13 - Enter
8 - Backspace
32 - Spacebar
posted on 12.01.2020 at 19:21
0pnshow more
TimTim
share on facebookshare on twitter
2020 AnswerTabsTermsContact us
This site uses cookies to improve your experience, for analytics and ads. By continuing to browse this site you agree to our use of cookies.