I am new to JavaScript and attempting to create a to-do list. How can I append an input with a checkbox attribute to my code so that paragraphs can be checked off once completed?
Here is my code below:
// ! DOM ELEMENTS
const taskInput = document.getElementById('taskInput');
const taskList = document.getElementById('taskList');
// ! ADD TASK
function addTask() {
if (taskInput.value === '') {
alert('Oh no... You have not written anything?');
} else {
let paragraph = document.createElement('p');
paragraph.textContent = taskInput.value;
taskList.appendChild(paragraph);
saveTasks();
}
taskInput.value = '';
}
<div class="container">
<h1>TO DO LIST</h1>
<input type="text" id="taskInput" placeholder="ENTER TASK HERE!">
<button id="addButton" click="addTask()">ADD</button>
<div id="taskList">
</div>
<p> lorem 10</p>
</div>
2
Answers
onClick
handler, not aclick
element.addEventListener('click')
insteaddocument.createElement
to make aninput
which you canappendChild
on theparagraph
You’re close but a bit of work needed here. For example let’s break this down to show how you can switch up things like your on click to event listener.
checkbox.type = 'checkbox'
: This line creates an input element and sets its type to "checkbox," which is what creates the clickable box.paragraph.prepend(checkbox)
: This is key! We useprepend
to insert the checkbox at the beginning of our paragraph, ensuring it appears before the task text.A minor change to the buttons too:
To the more common:
Note that we’ve removed the inline
onclick
and instead added theaddEventListener
in your JavaScript code earlier. These changes mean each new task will have a checkbox at the beginning of its line. And you can click the checkboxes to mark tasks as completed.