Appending input value to list using Javascript. To Do List - javascript

I am attempting to make a todo list.Not too sure why my code isn't working.Trying to get the value from the add item input to the To-Do ul.
HTML
<body>
<div class = 'container'>
<h3> Add Item </h3>
<input id='newTask' type='text'> <button id='addTaskButton'> Add </button>
<h3> To-Do </h3>
<ul id='toDo'>
<li> <input type='checkbox'<label> Learn Javascript </label> <button class='delete'> Delete </button> </li>
</ul>
<h3> Completed </h3>
<ul id='completedTasks'>
<li> <input type='checkbox' checked> <label> Buy Peanut Butter </label> <button class='delete'> Delete </button> </li>
</ul>
</div>
<script src = "todolist.js" type="text/javascript"></script>
</body>
Javascript
var taskInput = document.getElementById('newTask');
var addTaskButton = document.getElementById('addTaskButton');
var incompleteTasks = document.getElementById('toDo');
var completedTask = document.getElementById('completedTasks');
var addTask = function () {
var text = taskInput.value;
var li = '<li>' + text + '<li>';
incompleteTasks.appendChild(li);
}
addTaskButton.onclick = addTask;
Any help is greatly appreciated.
Thanks

appendChild accepts a DOMElement, not a string. You need to create an element first and then append it:
var addTask = function () {
var text = taskInput.value;
var li = document.createElement('li');
li.innerHTML = text;
incompleteTasks.appendChild(li);
}
Demo: http://jsfiddle.net/6wbsujL5/

Related

How can I insert elements in an array to a HTML document using Javascript?

I am trying to add the elements of a list called "taskList" made up of values I get from the input elements.
Can anyone please help me, I don't understand why the elements from the list are not showing.
var taskList = [];
var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
button.onclick = function(){
var nHTML = '';
var userEnteredText = input.value;
taskList.push(userEnteredText);
taskList.forEach(function(task){
nHTML += '<li>'+task+'</li>';
});
document.getElementsByClassName('taskLists').innerHTML = '<ul>' + nHTML + '</ul>';
}
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button" >➕</button>
</div>
<div class="taskLists">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button type="button" class="button">Clear All</button>
</div>
</div>
I tried checking several times but nothing is updating in the HTML document
You shouldn't append to innerHTML, instead, use createElement to make the li, then set innerHTML of that new element to input.value and use appendChild to append it to the list
var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
var tlist = document.getElementsByClassName('taskLists')[0];
button.onclick = function(){
let e = document.createElement('li');
e.innerHTML = input.value
tlist.appendChild(e)
// Optionally, clear the input field to prevent double adding the same task
input.value = '';
}
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button" >➕</button>
</div>
<div class="taskLists">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button type="button" class="button">Clear All</button>
</div>
</div>
The main mistake was using .getElementsByClassName like it was one element only and not a list (don't ignore the s in elements!).
Anyway I slightly refactored your code to have better strategies for each of its goals and implemented also the logic for clearing the tasks list.
var taskList = [];
var input = document.getElementById('takeInput');
var buttonAdd = document.getElementById('addInput');
var buttonClear = document.getElementById('clearInput');
var tasksList = document.getElementById('tasksList');
buttonAdd.addEventListener('click', (event)=>{
addTask(input.value);
});
buttonClear.addEventListener('click', (event)=>{
tasksList = [];
document.querySelector('#tasksList ul').remove();
});
function addTask(value){
if(taskList.length == 0){
document.getElementById('tasksList').append( document.createElement('ul') );
}
taskList.push(value);
const newLI = document.createElement('li');
newLI.innerText = value;
document.querySelector('#tasksList ul').append(newLI);
}
<body>
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button">➕</button>
</div>
<div id="tasksList">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button id="clearInput" type="button" class="button">Clear All</button>
</div>
</div>
</body>
you just needed to use an ID on the tasklist.
getElementsByClassName needs an index, making your question a dupe of What do querySelectorAll and getElementsBy* methods return?:
document.getElementsByClassName('taskLists')[0].innerHTML
That said, here is a full version using recommended eventListener and IDs where relevant.
let tasks = [];
const taskList = document.getElementById('taskLists')
const input = document.getElementById('takeInput');
const add = document.getElementById('addInput');
const pendingTasks = document.getElementById('pendingTasks');
const clear = document.getElementById('clear');
const showTasks = () => {
taskList.innerHTML = `<ul>${tasks.map(task => `<li>${task}</li>`).join('')}</ul>`;
pendingTasks.textContent = `${tasks.length} task${tasks.length != 1 ? "s" : ""}`;
};
add.addEventListener('click', () => {
var userEnteredText = input.value;
tasks.push(userEnteredText);
showTasks();
});
clear.addEventListener('click', () => {
tasks = [];
showTasks();
});
taskList.addEventListener('click', (e) => {
const tgt = e.target.closest('li');
if (!tgt) return; // not a task
const task = tgt.textContent;
tgt.remove()
tasks = tasks.filter(currentTask => currentTask != task); // remove from list
showTasks()
});
showTasks(); //init
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button">➕</button>
</div>
<div id="taskLists"></div>
<div class="footer">
<span> You have <span id="pendingTasks"></span> left </span>
<button type="button" id="clear">Clear All</button>
</div>
</div>

How can I add the functionality to delete and edit an item in a "To Do List" with JavaScript only?

I am learning JavaScript and I am trying to create a to list. I have successfully been able to:
add new items to the list and able to cross off when each item is clicked
Append an edit button to each new item
I need help with this functionality:
add a trash can icon when the item is added
be able to add an event listener to each icon so that is deleted when clicked
3)Be able to edit each item and save it when the edit button is clicked
Any help would be appreciated!
https://codepen.io/stefan927/pen/qBVLpxm
"<html>
<body onload="taskComplete()">
<div class="card">
<div class="card-body">
<h3 class="card-title" id="header">Today's To Do List</h3>
<form id="todo-form">
<div class="input">
<input type="text" onfocus="this.value=''"
class="form-
control" id="todo-input" value="What do I want to do?">
</div>
<div class="form-group">
<input type="button" onclick = "addItemToTheList()"
class="btn btn-secondary btn-block" value="Add">
<p> Click an item to cross it off! </p>
</div>
</form>
</div>
<ul class="list-group list-group-flush" id="todo-list">
<li class="list-group-item">Pick up groceries
<i class="fas fa-trash-alt"></i> <button
class="edit">Edit</button>
</li>
<li class="list-group-item">Finish essay
<i class="fas fa-trash-alt"></i><button
class="edit">Edit</button>
</li>
<li class="list-group-item">Soccer # 5:00
<i class="fas fa-trash-alt"></i><button
class="edit">Edit</button>
</ul>
</div>
</body>
</html>"
"// Create an alert that asks for user name and then add it to
the heading.
//var name = prompt("Hello my name is");
//alert("Hello, " + name);
header.innerText = name + "'s To Do List";
// Define variables
var newItem = document.createElement("li");
var input = document.getElementById("todo-input");
var icon = "fas fa-trash-alt";
var i = document.createElement('i');
var editInput = document.createElement("input");
//button.edit
var editButton = document.createElement("button");
//button.delete
editButton.innerText = "Edit";
editButton.className = "edit";
// create a function that adds new items to the list with a trash
icon
function addItemToTheList() {
newItem.innerHTML = input.value;
input.value = "";
document.getElementById("todo-list").appendChild(newItem);
newItem.appendChild(editButton);
// Add click listener
newItem.addEventListener('click', done);
}
function done() {
this.className = "done";
this.removeEventListener('click',done);
}
// Initialize all listener for current undone tasks
function taskComplete() {
var undoneItems = document.getElementsByClassName('undone');
for(var i = 0; i < undoneItems.length; i++){
undoneItems[i].addEventListener('click', done);
}
// Delete item from list when trash icon is clicked
function deleteItem() {
i.onclick = deleteItem;
li.setAttribute('id', input.value);
li.classList.add("list-group-item");
i.className = icon;
}
//Edit an existing task
var editTask = function(){
console.log("Edit task...");
var listItem = this.parentNode;
var editInput = listItem.querySelector("input[type=text]");
var label = listItem.querySelector("label");
var containsClass = listItem.classList.contains("editMode");
//if the class pf parent is .editmode
if (containsClass){
//label text become the input's value
label.innerText = editInput.value;
} else {
//switch to .editmode
//input value becomes the label's text
editInput.vaule = label.innerText;
}
listItem.classList.toggle("editMode"); //toggle .editmode on the
parent
}
}"

create list item from input value

I'm working on a to-do list project and I got a problem, I want that when I click on the submit button the input value becomes a list item but it doesn't work.
here's the code:
let btn = document.getElementById('btn')
let txt = document.getElementById('txt')
btn.addEventListener('click', function(){
let list = document.createElement('li')
list.innerHTML = txt.value
})
<h1 id="title">To do list</h1>
<div class="main">
<input type="text" alt="type text here" id="txt">
<button type="submit" id="btn">Submit</button>
</div>
you forgot document.body.appendChild(list);
You need to have a ul (if it is to be an unordered list) element in your document - or to create one with JS, and then you need to add the new list items to that (not to the body).
Try this snippet (where the ul element is already in the document)
let btn = document.getElementById('btn')
let txt = document.getElementById('txt')
let ul = document.getElementById('ul');
btn.addEventListener('click', function() {
let list = document.createElement('li')
list.innerHTML = txt.value;
ul.appendChild(list);
})
<h1 id="title">To do list</h1>
<div class="main">
<input type="text" alt="type text here" id="txt">
<button type="submit" id="btn">Submit</button>
</div>
<ul id="ul">
</ul>

How to save data after refreshing a page

Here is my script of to do list. I wanna add a new note to my ul list.
li > p > i, i, input :
var list = document.querySelector('.list');
document.querySelector('.add-btn').addEventListener('click', function(e){
e.preventDefault();
var input = document.querySelector('.add-input');
if(input.value !== '') {
var li = document.createElement('li');
firstP = document.createElement('p');
secondP = document.createElement('p');
firstIc = document.createElement('i');
secondIc = document.createElement('i');
input1 = document.createElement('input');
firstIc.className = 'fas fa-edit';
secondIc.className = 'fas fa-trash-alt';
input1.className = 'edit-note';
input1.setAttribute('type', 'text');
firstP.textContent = input.value;
secondP.appendChild(firstIc);
secondP.appendChild(secondIc);
li.appendChild(firstP);
li.appendChild(secondP);
li.appendChild(input1);
li.appendChild(li);
}
});
Here is HTML:
<div class='container'>
<h1>Note manager</h1>
<ul class="list">
<li>
<p>First note</p>
<p><i class="fas fa-edit"></i><i class="fas fa-trash-alt"></i></p>
<input type="text" name="" class="edit-note">
</li>
<li>
<p>Second note</p>
<p><i class="fas fa-edit"></i><i class="fas fa-trash-alt"></i></p>
<input type="text" name="" class="edit-note">
</li>
</ul>
<div class="add-notes">
<input type="text" name="" class="add-input" placeholder="Add a note..">
<button type="submit" class="add-btn"> Add</button>
</div>
</div>
And I wanna save added notes when I refresh the page. How can I do this ?
Should I use AJAX >?
Look at this line:
li.appendChild(li);
Here you add element as child of itself (of course it's not possible), looks like you want to do
list.appendChild(li);
instead.
EDIT:
Answer to your updated question: you should post your items to server and save them there or you can use localStorage to keep items in browser (link)

Sample To Do List in javascript : completed tasks problems

function todoList() {
var item = document.getElementById('todoInput').value
var text = document.createTextNode(item)
var newItem = document.createElement("li")
newItem.appendChild(text)
var completed_button = document.createElement('input');
completed_button.type = "button";
completed_button.value = "Completed";
newItem.appendChild(completed_button);
document.getElementById("todoList").appendChild(newItem)
}
<h1>My To Do list</h1>
<form id="todoForm">
<input id="todoInput">
<button type="button" onclick="todoList()">Add Item</button>
</form>
<ul id="todoList">
<h3>My Tasks</h3>
</ul>
<ul>
<h3>Completed</h3>
</ul>
When I click on the completed button, I want to delete it from My Tasks and add it to the Completed ones. Can you help?
I played a little with your code and ended up with that snippet:
(I left comments in the code)
function todoList() {
var item = document.getElementById('todoInput').value
var text = document.createTextNode(item)
var newItem = document.createElement("li")
newItem.appendChild(text)
var completed_button = document.createElement('input');
completed_button.type = "button";
completed_button.value = "Completed";
completed_button.onclick = function() { // Added the onclick function
clickComplete(this);
};
newItem.appendChild(completed_button);
document.getElementById("todoList").appendChild(newItem);
}
// Added this function
function clickComplete(item) {
document.getElementById("completed").appendChild(item.parentNode);
item.remove(); // Removes the "completed" button
}
<h1>My To Do list</h1>
<form id="todoForm">
<input id="todoInput">
<button type="button" onclick="todoList()">Add Item</button>
</form>
<ul id="todoList">
<h3>My Tasks</h3>
</ul>
<ul id="completed">
<h3>Completed</h3>
</ul>
Feel free to comment me if any modification is to be made in that snippet.
Hope it helps.

Categories