Home > Back-end >  create list item from input value
create list item from input value

Time:10-07

I'm working on a to-do list project and I got a problem, I want that when I click on the submit button the input value becomes a list item but it doesn't work. here's the code:

let btn = document.getElementById('btn')
let txt = document.getElementById('txt')

btn.addEventListener('click', function(){
    let list = document.createElement('li')
    list.innerHTML = txt.value
})
<h1 id="title">To do list</h1>
    <div class="main">
        <input type="text" alt="type text here" id="txt">
        <button type="submit" id="btn">Submit</button>
    </div>

CodePudding user response:

you forgot document.body.appendChild(list);

CodePudding user response:

You need to have a ul (if it is to be an unordered list) element in your document - or to create one with JS, and then you need to add the new list items to that (not to the body).

Try this snippet (where the ul element is already in the document)

let btn = document.getElementById('btn')
let txt = document.getElementById('txt')
let ul = document.getElementById('ul');

btn.addEventListener('click', function() {
  let list = document.createElement('li')
  list.innerHTML = txt.value;
  ul.appendChild(list);
})
<h1 id="title">To do list</h1>
<div class="main">
  <input type="text" alt="type text here" id="txt">
  <button type="submit" id="btn">Submit</button>
</div>
<ul id="ul">
</ul>

  • Related