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 ?
11 Jan 2020 at 12:49 PM
0give a positive ratinggive a negative ratingshow more

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:

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'); }

<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
12 Jan 2020 at 07:21 PM
0give a positive ratinggive a negative ratingshow more
Share on FacebookShare on TwitterShare on LinkedInSend email
Follow us on Facebook
2022 AnswerTabsTermsContact us