I’m a beginner at using Javascript or just beginner in general. I’m having a little trouble with this function I created. It is supposed to create a list based on the previous function that I have created.
What I expect is the browser to create a new list every time a input is made with a set of values that were made.
const form = document.getElementById('todoForm')
const todoInput = document.getElementById('todoInput')
if (typeof document !== 'undefined') {
let element = document.querySelector('.class-name')
}
let todos = []
form.addEventListener('submit', event => {
event.preventDefault()
saveTodo();
})
function saveTodo() {
const todoValues = todoInput.value;
let values = {
value: todoValues,
checked: false,
color: '#' + Math.floor(Math.random() * 16777215).toString(16),
length: todoValues.length
}
todos.push(values)
addTask()
}
// add task and adds to the list
function addTask() {
let task = document.createElement('li')
task.appendChild(document.getElementById(todos))
}
console.log(todos)
<h1 class="title">ToDo List</h1>
<form action="#" class="todoForm" id="todoForm">
<input type="text" placeholder="Text" id="todoInput" />
<button id="btn-form" class="btn-form">Enter</button>
</form>
2
Answers
There are quite a few logical errors here.
It sounds like you have a list of
tasks
and it is stored intodo
variable.So when you are calling
addTask()
you want it either to receive the (1) new task as an argument or (2)use thetodos
variable.(1) in this case you need to create a
<li>
list element based on the new task, find<ul>
element and then append the new one to<ul>
(2) clear
<ul>
element, for each task in todos do (1).As a sidenote:
let values = {....
should be better called ‘value’ as it represents a single task.This is probably what you need
<ul>
element to your HTML so you can append there your list of task.let todoInput = document.getElementById('todoInput')
moved this line inside yoursaveTodo()
function becuz you have to get the value of your input right after you press the button, otherwise you will get an empty value