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

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
give a positive ratinggive a negative rating
12 Jan 2020 at 07:21 PM
Share on FacebookShare on TwitterShare on LinkedInSend email
2024 AnswerTabsTermsContact us