Home > Back-end >  How to let user to type in the type box and then push that value to the list?
How to let user to type in the type box and then push that value to the list?

Time:07-31

Currently, I am using this code:

var todoList = [
  "Take a shower"
];

function addItem() {
  var inputs = document.getElementById('new-item');
  var newItem = inputs.value;
  todoList.push(newItem);
  render();
  inputs.value = "";
}

function render() {
  var htmlList = document.getElementById('todo-List');
  var content = todoList.map(function(item) {
    return "<li>"   item   "</li>"

  });

  htmlList.innerHTML = content.join('');
}

render()
<section id="story">
  <input id="new-item" type="text" />
  <button onclick="addItem()">Add</button>
  <ul id="todo-list"></ul>

I want to let users type in the type box(<input id="new-item" type="text"/>) and when they click the Add button(<button onclick="addItem()">Add</button>) the value in the type box will be pushed to the <ul> list.The problem is my code above does not work, can you tell me what is wrong with my code and how to fix that problem? Thank you.

CodePudding user response:

your code is fine, you just wrote wrong document.getElementById('todo-list'); be document.getElementById('todo-List');

CodePudding user response:

You had a typo in your code, as you wrote todo-List instead of todo-list.

var todoList = [
  "Take a shower"
];

function addItem() {
  var inputs = document.getElementById('new-item');
  var newItem = inputs.value;
  todoList.push(newItem);
  render();
  inputs.value = "";
}

function render() {
    // corrected the "todo-List" typo below:
  var htmlList = document.getElementById('todo-list');
  var content = todoList.map(function(item) {
    return "<li>"   item   "</li>"

  });

  htmlList.innerHTML = content.join('');
}

render()
<section id="story">
  <input id="new-item" type="text" />
  <button onclick="addItem()">Add</button>
  <ul id="todo-list"></ul>
</section>

  • Related