I am a complete noob and I have started trying to do a program which plays the sound of each letter’s keycode every time it is pressed in the textbox and deletes the text every time I press the Spacebar.
The program clears the textbox when I use the space button, but it doesn’t play sound with any character:
<!DOCTYPE html> <html lang="en"> <head> <title>keyCode example</title> <script type="text/javascript"> function showKeyCode(e) { var letter = e.keyCode if (letter != 32) { var audio = new Audio(e.keyCode + ".wav"); audio.play(); } else { document.getElementById("TextBox1").value = ""; } } </script> </head> <body> <input TYPE = text ID="TextBox1" SIZE = 15 onkeyup="showKeyCode(event);"> </body> </html>
Advertisement
Answer
Okay, I found a few problems in your code:
Don’t use uppercase tag attributes.
Use quotes for attributes.
Include the
<body>
tag.You forgot a semicolon after
var letter = e.keyCode
.function showKeyCode(e) { var letter = e.keyCode; if (letter != 32) { var audio = new Audio(e.keyCode + ".wav"); audio.play(); } else { document.getElementById("TextBox1").value = ""; } }
I have made a jsFiddle for you. It seems to work.
Furthermore, why do you use onkeyup
and not onkeydown
?