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
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
Share on FacebookShare on TwitterShare on LinkedInSend email
1 answer
x
x
2024 AnswerTabsTermsContact us