Max Muchnick
Max Muchnick

Reputation: 55

How to add user input from a text box to a list in HTML

I'm trying to add input from a text box to a list in HTML. I've tried a few things and searches other stack overflow questions and got to the code below. The user input works, it just doesn't output to the list. Overall what I want the code to do is have the list display all the items that get typed into the text box.

<!DOCTYPE html>
<html>
<head>

</head>
<body>


  <script type="text/javascript">

document.getElementById("add").onclick = function() {

    var text = document.getElementById("input").value; 
    var li = "<li>" + text + "</li>";


    document.getElementById("list").appendChild(li);
}

</script>

<input type='text' id='input' />
<input type='button' value='add to list' id='add' />

<ul id='list'>
  <li> <b>Topics</b></li> 
  </ul>

</body>
</html>

Upvotes: 2

Views: 8168

Answers (2)

Mamun
Mamun

Reputation: 68933

Since you are trying to append htmlString into the element try with

Element.insertAdjacentHTML()

document.getElementById("add").onclick = function() {
  var text = document.getElementById("input").value; 
  var li = "<li>" + text + "</li>";
  document.getElementById("list").insertAdjacentHTML('beforeend', li);
  document.getElementById("input").value = ""; // clear the value
}
<input type='text' id='input' />
<input type='button' value='add to list' id='add' />

<ul id='list'>
  <li> <b>Topics</b></li> 
</ul>

OR: Using Element.innerHTML:

document.getElementById("add").onclick = function() {
  var text = document.getElementById("input").value; 
  var li = "<li>" + text + "</li>";
  document.getElementById("list").innerHTML += li;
  document.getElementById("input").value = ""; // clear the value
}
<input type='text' id='input' />
<input type='button' value='add to list' id='add' />

<ul id='list'>
  <li> <b>Topics</b></li> 
</ul>

Though I prefer using Document.createElement() to create the HTML element which is allowed as parameter by Node.appendChild():

document.getElementById("add").onclick = function() {
  var text = document.getElementById("input").value; 
  var li = document.createElement("li");
  li.textContent = text;
  document.getElementById("list").appendChild(li);
  document.getElementById("input").value = ""; // clear the value
}
<input type='text' id='input' />
<input type='button' value='add to list' id='add' />

<ul id='list'>
  <li> <b>Topics</b></li> 
</ul>

Upvotes: 6

User863
User863

Reputation: 20039

use document.createElement() which creates the HTML element specified by tagName

document.getElementById("add").onclick = function() {
  var text = document.getElementById("input").value;

  var li = document.createElement("li");
  li.innerText = text;

  document.getElementById("list").appendChild(li);
}
<input type='text' id='input' />
<input type='button' value='add to list' id='add' />

<ul id='list'>
  <li> <b>Topics</b></li>
</ul>

Upvotes: 1

Related Questions