user2581598 user2581598 - 3 months ago 12
Javascript Question

Add a list item through javascript

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. Please help! Here is the code below:

<!DOCTYPE html>
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;
document.getElementById('demo').innerHTML = x;

<p>Your first name is: <b id='boldStuff2'></b> </p>
<p> Other people's names: </p>

<li id = "demo"> </li>

<input type='button' onclick='changeText2()' value='Submit'/>



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