0

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>

2 Answers 2

2

You're appending newli over and over again:

node.appendChild(newli);

So, on subsequent enters, 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>

Sign up to request clarification or add additional context in comments.

Comments

1

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 );

    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.