I am a beginner learning JavaScript at present and I want to make a to-do app as my first project in javascript but there seems to be some complications. Firstly, i can create an empty list which suppose not to occur secondly, I can't delete a single To-do list. I know my code is not okay but I will be happy if someone can solve it this way. Thanks in advance source code below
HTML CODE
<div><input type ="text"id="input-el" placeholder="Enter your list of to do here...">
<button id="save-el">createlist</button>
<button id="delete-el">Delete list </button>
<div>
<ul id="ul-el"></ul>
//Javascript CODE
let todo = [];
let inputEl = document.getElementById("input-el");
const saveEl = document.getElementById("save-el");
const deleteEl = document.getElementById("delete-el");
const xEl = document.getElementById("x-el");
let items= document.getElementById("items");
let ulEl = document.getElementById("ul-el");
let listItems = ""
//FUNCTION USE TO ADD NEW TO-DO LIST
function myfunc(){
let listItems = ""
for(let i=0;i<todo.length;i++) {
listItems += `
<li id='${items}'><span>
<input class='check' type ='checkbox'></span>${todo[i]} <button id='x-el'>x</button></li>
`
}
ulEl.innerHTML = listItems;}
//SAVE TO-DO LIST
if(inputEl !== ""){ saveEl.addEventListener("click",function(){
todo.push(inputEl.value);
inputEl.value = "";
myfunc()
})
}
else {
alert("can't create an empty list")
}
//TO DELETE ALL TO-DO LIST
deleteEl.addEventListener("dblclick",function(){
todo = [];
saveEl.value = "";
inputEl.value = "";
myfunc()
})
//TO REMOVE A SINGLE TO-DO LIST FROM ALL LIST
/*items.addEventListener('click',
function(e) {
this.removeChild(e.target);
})*/
I comments some codes out when it doesn't work, I will be happy if you can solve this issue using my approach
This project can be done without using an array to store tasks. I hope this will solve your problem.
<html>
<body>
<input type="text" id="inputEl" placeholder="Enter your list of to do here...">
<button id="saveEl">createlist</button>
<button id="deleteEl">Delete list</button>
<ul id="ulEl"></ul>
<script>
let inputEl = document.getElementById("inputEl")
let saveEl = document.getElementById("saveEl")
let ulEl = document.getElementById("ulEl")
let deleteEl = document.getElementById("deleteEl")
//ADD NEW ELEMENT TO LIST
saveEl.addEventListener("click", function() {
var task = document.createElement("li")
task.innerText = inputEl.value
ulEl.appendChild(task)
//REMOVE SINGLE TASK
task.addEventListener("click", function() {
ulEl.removeChild(task)
})
})
//DELETE ALL ELEMENTS
deleteEl.addEventListener("dblclick", function() {
ulEl.innerText = ""
})
</script>
</body>