So I'm still learning javascript and for my first to do list project I've gotten to the point where I can add the array to the HTML page but instead of taking the last element and adding it it adds the whole array to each line. How do I change it so only the last element is added instead?
HTML
<!DOCTYPE html>
<html>
<head>
<title>Task Tracker</title>
<link rel="stylesheet" type="text/css" href="todo.css">
<script type="text/javascript" src="todo.js"></script>
</head>
<body>
<div>
<p>Task Manager</p>
<input type="text" name="submitButton" id="userInput">
<button onclick=addTask()>Enter</button>
</div>
<div>
<h3>Task</h3>
<div id='taskList'>
<ul id="myList">
</ul>
</div>
</div>
</body>
</html>
JavaScript
let Task = [];
function addTask(){
var newTask = document.getElementById("userInput").value;
Task.push(newTask);
updateTaskList();
};
function updateTaskList(){
var node = document.createElement('LI');
var textNode;
for (let i = Task.length - 1; i >= 0; i -= 1){
textNode = document.createTextNode(Task[i]);
console.log(Task[i]);
node.appendChild(textNode);
document.getElementById("myList").appendChild(node);
}
}
Instead of using two functions, you can combine this into one function, the code would look like this
function addTask() {
let node = document.createElement("li");
let textNode = document.createTextNode(
document.getElementById("userInput").value
);
node.appendChild(textNode);
document.getElementById("myList").appendChild(node);
}
As an aside, it is best not to use the var keyword anymore and replace it with let, (or if you aren't reassigning it, const) because let is block-scoped (most of the time it doesn't matter, but var can have weird issues)
As a bonus, you could figure out how to remove an list item when the user clicks the list item and add an edit button that lets them edit them
Another good thing would be to set a localStorage array to keep the data of the website so when the user reloads it saves their list items
If you want to get really advanced, you would set up a backend database and set up user authentication
If you want to get deeper into coding/javascript, I strong suggest udemy courses (only when they are on sale though)
Hope this helps and happy coding!!