user9413954
user9413954

Reputation:

How to clear text input box on pressing enter (in a div)?

I'm trying to set up a input box using a div, but I'm having some difficulty finding how to clear the text box upon pressing enter.

I've searched for a solution and have found this code that uses an eventListener and a function.

var messageinputbox = document.createElement("input"); 

messageinputbox.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
    event.preventDefault();
    document.getElementById('chatbox').value = "";
  }
});

document.getElementById("messageinput").appendChild(messageinputbox);

The fuction does not work, even though I do not see any syntax errors in it, and my javascript file doesn't give me any errors.

Upvotes: 0

Views: 44

Answers (2)

Hedego
Hedego

Reputation: 294

Try this sample code: <html> <head> <title>Javascript key press demo</title> <script type='text/javascript'> function clearTextonEnterKeyPress(e){ if(e.keyCode == 13){ alert("You Have Pressed Enter Key."); document.getElementById('test').value = ""; alert('Text Cleared'); } } </script> </head> <body> Press Enter Button in text box <input type='text' onkeypress='clearTextonEnterKeyPress(event)' id='test'> </body> </html>

Upvotes: 0

Barmar
Barmar

Reputation: 780655

You never gave the new input box the ID chatbox. You need

messageinputbox.id = "chatbox";

But there's no need for the ID, since the messageinputbox variable holds a reference to the input box. Just use that variable in the function.

var messageinputbox = document.createElement("input"); 

messageinputbox.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
    event.preventDefault();
    messageinputbox.value = "";
  }
});

document.getElementById("messageinput").appendChild(messageinputbox);
<div id="messageinput"></div>

Upvotes: 3

Related Questions