Reputation: 1
In HTML i have input of type text and unordered list. when an enter is hit in the input, the text entered should be grabbed and added to the list. How can i achieve it using javascript without any library?
The below code is what i've written but it not creating the list as expected. it is creating blank li and adding everything to the last li
var newli = document.createElement("li");
var inp = document.getElementsByTagName("input");
var ul = document.getElementsByTagName("ul")[0];
inp[0].addEventListener("keypress", function(event){
if(event.which===13){
var inputText = this.value;
this.value = " ";
var node = document.createElement("LI");
newli.appendChild(document.createTextNode(inputText));
node.appendChild(newli);
ul.appendChild( node );
}
});
<input type="text">
<ul>
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
</ul>
Upvotes: 0
Views: 111
Reputation: 21406
Your script needs to be as below. You need to comment some of your lines. Read my comments just above the commented line for explanation.
You can see a full sample at: Running Sample
//no need of line below as a new li is being created in keypress event
//var newli = document.createElement("li");
var inp = document.getElementsByTagName("input");
var ul = document.getElementsByTagName("ul")[0];
inp[0].addEventListener("keypress", function(event){
if(event.which===13){
var inputText = this.value;
this.value = " ";
var node = document.createElement("LI");
node.appendChild(document.createTextNode(inputText));
//no need of line below as above line is already appending to new li some text
//node.appendChild(newli);
ul.appendChild( node );
}
});
Upvotes: 1
Reputation: 4097
You're appending newli
over and over again:
node.appendChild(newli);
So, on subsequent enter
s, it gets removed from its previous position in the DOM. Create a new LI inside the event handler instead:
const input = document.querySelector('input');
const ul = document.querySelector('ul');
input.addEventListener("keypress", function(event) {
if (event.which === 13) {
this.value = "";
const newli = document.createElement("li");
newli.textContent = this.value;
ul.appendChild(newli);
}
});
<input type="text">
<ul>
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
</ul>
Upvotes: 2