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