简体   繁体   中英

creating list dynamically from the input of type text

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> 

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> 

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

    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM