The checkbox that is created next to the task can not be set to the checked position, which would create a line across the task. When opening console I don’t get any errors, only the following error:
A form field element has neither an id nor a name attribute
When clicking on the checkbox increments up.
I don’t know how to assign a name or attribute to the checkbox, as this is what I assume the problem is.
This is the function that would create the list items with checkboxes:
and the CSS class that crosses off the listed item.
let tasks = [];
function addTask() {
const taskInput = document.getElementById("addTaskInput");
const taskText = taskInput.value.trim();
if (taskText !== "") {
tasks.push({ text: taskText, completed: false });
renderTasks();
taskInput.value = "";
}
}
function toggleTask(index) {
tasks[index].complete = !tasks[index].completed;
renderTasks();
}
function deleteTask(index) {
tasks.splice(index, 1);
renderTasks();
}
function renderTasks () {
const taskList = document.getElementById("added-task")
taskList.innerHTML = "";
tasks.forEach((task, index) => {
const li = document.createElement("li");
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = task.completed;
checkbox.addEventListener("change", () => toggleTask(index));
li.appendChild(checkbox);
const taskText = document.createElement("span");
taskText.textContent = task.text;
taskText.className = "task" + (task.completed ? " complete " : "");
li.appendChild(taskText);
const deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.className = "delete-btn"
deleteBtn.addEventListener('click', () => deleteTask(index));
li.appendChild(deleteBtn);
taskList.appendChild(li);
});
}
.task.completed {
text-decoration: line-through;
color: #ccc;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="title">To Do List</h1>
<div class="container">
<input type="text" id="addTaskInput" placeholder="Add Task">
<button class="add-task-btn" onclick="addTask()">Add Task</button>
<ul id="added-task"></ul>
</div>
<script src="config.js"></script>
</body>
</html>
2
Answers
Your are facing error not due to checkbox but due to handling
<input>
and<button>
. I have formatted this code below as per your requirement.Please let me know if it works for you :
Since your code is a bit incomplete, I tried to improvise and re-wrtitten it in bare minimal form.
You can add validation is addTask method to check unique task names, input length etc.