0

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>

2
  • 1
    Does this answer your question? Add an element to the DOM with JavaScript Commented Oct 6, 2021 at 16:14
  • If the button is in a form, the form submit will happen before the JS completes. You either need to interrupt the default action of a submit button or change the button to type button in order to allow any JS DOM manipulation to occur Commented Oct 6, 2021 at 16:19

2 Answers 2

2

you forgot document.body.appendChild(list);

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.