Skip to content
Advertisement

Playing audio from characters of a textbox using JavaScript

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:

  1. Don’t use uppercase tag attributes.

  2. Use quotes for attributes.

  3. Include the <body> tag.

  4. 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?

Advertisement