Yoav Linder
Yoav Linder

Reputation: 123

clearing the text box after pressing enter key

i have been trying to clear the text box after pressing the enter key, but i couldn't find any solution for this, been searching for over 2 hours.. this is the code:

html:

<!DOCTYPE html>
<html>
<body>
<style>
input{
margin-top:300px;
margin-left:580px;
}
ul{
margin-left:580px;
}
</style>
<input type="text" id="textBox" value = "" />
<ul id="dynamic-list"></ul>

<script src="script.js"></script>
</body>
</html>

javascript:

 function addItem(){
        var ul = document.getElementById("dynamic-list");
        var candidate = document.getElementById("textBox");
        var li = document.createElement("li");
        li.setAttribute('id',candidate.value);
        li.appendChild(document.createTextNode(candidate.value));
        ul.appendChild(li);
        document.getElementById('candidate').value = "";
        document.getElementById('textBox').value = "";
    }
    var input = document.getElementById("textBox");
    input.addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode === 13) {
            addItem();
        }

    });

Upvotes: 0

Views: 2073

Answers (1)

31piy
31piy

Reputation: 23859

There is no element whose ID is candidate in your HTML code. So JavaScript throws and error and stops executing the next statement. That's why the textbox doesn't clean up.

Remove the buggy statement, and your code works just fine:

function addItem() {
  var ul = document.getElementById("dynamic-list");
  var candidate = document.getElementById("textBox");
  var li = document.createElement("li");
  li.setAttribute('id', candidate.value);
  li.appendChild(document.createTextNode(candidate.value));
  ul.appendChild(li);
  document.getElementById('textBox').value = "";
}
var input = document.getElementById("textBox");
input.addEventListener("keyup", function(event) {
  event.preventDefault();
  if (event.keyCode === 13) {
    addItem();
  }

});
<input type="text" id="textBox" value="" />
<ul id="dynamic-list"></ul>

Upvotes: 1

Related Questions