Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a list item through JavaScript

Tags:

javascript

dom

So, I am trying to print out an array that gets user input text added to it, but what I want to print out is an ordered list of the array. As you can see, (if you run my code) the list item just keeps getting the user input added to it, and no new list items are added with people's names.

Here is the code below:

 <!DOCTYPE html>  <html>  <head>  First name: <input type="text" id="firstname"><br>    <script type="text/javascript">  var x= [];   function changeText2(){ var firstname = document.getElementById('firstname').value; document.getElementById('boldStuff2').innerHTML = firstname; x.push(firstname); document.getElementById('demo').innerHTML = x;  }  </script>   <p>Your first name is: <b id='boldStuff2'></b> </p>   <p> Other people's names: </p>    <ol>      <li id = "demo"> </li>   </ol>   <input type='button' onclick='changeText2()'   value='Submit'/>    </head>  <body>  </body>  </html> 
like image 673
user2581598 Avatar asked Jul 21 '13 15:07

user2581598


People also ask

How do you add an item to a list in HTML?

In HTML, we can create an ordered list using the <ol> tag. The ol in the tag stands for an ordered list. Inside each of the ordered list elements <ol> and <ol /> , we have to define the list items. We can define the list items using the <li> tag.

What is append in JavaScript?

append() The Element. append() method inserts a set of Node objects or string objects after the last child of the Element . String objects are inserted as equivalent Text nodes.

How do I append to innerHTML?

To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.


2 Answers

If you want to create a li element for each input/name, then you have to create it, with document.createElement [MDN].

Give the list the ID:

<ol id="demo"></ol> 

and get a reference to it:

var list = document.getElementById('demo'); 

In your event handler, create a new list element with the input value as content and append to the list with Node.appendChild [MDN]:

var firstname = document.getElementById('firstname').value; var entry = document.createElement('li'); entry.appendChild(document.createTextNode(firstname)); list.appendChild(entry); 

DEMO

like image 102
Felix Kling Avatar answered Sep 21 '22 16:09

Felix Kling


Try something like this:

var node=document.createElement("LI"); var textnode=document.createTextNode(firstname); node.appendChild(textnode); document.getElementById("demo").appendChild(node); 

Fiddle: http://jsfiddle.net/FlameTrap/3jDZd/

like image 41
Flame Trap Avatar answered Sep 22 '22 16:09

Flame Trap