I’m in a programming course and I need to create a “To-Do” list page using javascript and HTML. Whatever the user types in the text box should show up below a "To-Do List" heading lower on the page. I’m having trouble getting the information submitted in the form to show up on the page below the To Do list heading. Here’s my code so far.
const formE1 = document.getElementById('todo-form');
const inputE1 = document.getElementById('todo-item');
const list = document.getElementById('to-do');
formE1.addEventListener('submit', function(event) {
event.preventDefault();
const li = document.getElementById('the-list');
document.createElement('li');
inputE1.appendChild(li);
console.log(formE1)
})
const input = document.querySelector('ol');
let template = ''
for (let i = 0; i < inputE1.length; i ) {
const item = `
<li>
<p>Name: ${inputE1}</p>
</li>
`
template = item;
}
input.innerHTML = template;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forms</title>
</head>
<body>
<h1>Add a Todo</h1>
<div id="todo-list">
<form id="todo-form">
<input type="text" id="todo-item" placeholder="List Item"/>
<input type="submit" id="todo-add" value="Submit"/>
</form>
<div id="to-do">
<h2>To-Do List</h2>
<ol id="the-list"></ol>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
CodePudding user response:
The key thing is that you were trying to execute code outside of the handler.
You can simplify your code a little. There's no real need for a form
element, for example, so add the listener to your button.
const button = document.querySelector('button');
const input = document.querySelector('input');
const list = document.querySelector('ol');
button.addEventListener('click', function(e) {
const li = document.createElement('li');
li.textContent = input.value;
list.appendChild(li);
});
<h1>Add a Todo</h1>
<div>
<input type="text" placeholder="List Item" />
<button type="button">Submit</button>
<div>
<h2>To-Do List</h2>
<ol></ol>
</div>
</div>