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>
Related
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>
I have a list of items to put in a box and i have an empty box, the list of items and the empty box are two different arrays, the items are objects in the array put by user inputs. Beside every item added is an "add" button appended to it which should then copy that selected object into the empty box array. How do i achieve this?
i have tried to append the parentNode of the add button and push to the new array but it just pushed the "Li" element instead of the object itself
<div>
<input id="userinput" type="number" placeholder="Enter Capacity">
<button id="enter">Enter</button>
</div><br>
<div>
<p>Items Information:</p>
<input id="itemName" type="text" placeholder="enter item name">
<input id="itemWeight" type="number" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" placeholder="enter item value">
<button onclick="addListAfterClick()" id="value">Enter</button>
</div>
<ul id="list">LIST OF 20 ITEMS TO CHOOSE FROM
</ul>
<ul id="knap"> LIST OF ITEMS IN KNAPSACK
</ul>
<div>
let addValues = () =>{
inputs = {
name : input2.value,
weight : parseFloat(input3.value),
value : parseInt(input4.value)
}
arr_items.push(inputs);
console.log(arr_items);
createListElement();
}
let createListElement = () => {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input2.value));
ul.appendChild(li);
let btn = document.createElement("button");
btn.appendChild(document.createTextNode("Add"));
li.appendChild(btn);
btn.onclick = addTo;
}
function addTo(){
var li2 = document.createElement("li");
li2.appendChild(document.createTextNode(input2.value));
ul2.appendChild(li2);
knap.push(this.parentNode);
console.log(knap);
}
I expect any object clicked to be copied to the "knap" array
First of all, your question was confusing, your code was not so clear as you didn't define most of the variables and function you called up in the code, I found it difficult understanding what you meant.
If you want to do this, you have to actually keep track of all the list items you are creating, to do this I created a listCount variable that increments whenever the "Add" button is clicked, I set the id of the "Add" button to the current value of the listCount variable. So when "Add" button is clicked, we retrieve id and use it to select which array to push to "knap" from the "arr_list". Here is the modification of your code:
arr_items = new Array();
knap = new Array();
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
let ul = document.getElementById("list");
let ul2 = document.getElementById("knap")
let listCount = 0; // create a listCount variable to track the list items created
let addValues = () =>{
inputs = {
name : input2.value,
weight : parseFloat(input3.value),
value : parseInt(input4.value)
}
arr_items.push(inputs);
console.log(arr_items);
createListElement();
}
let createListElement = () => {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input2.value));
ul.appendChild(li);
let btn = document.createElement("button");
btn.appendChild(document.createTextNode("Add"));
li.appendChild(btn);
btn.id = listCount; // set the value of listCount variable as the id of the button
btn.onclick = addTo;
listCount++; // increment the list count variable
}
function addTo(){
var li2 = document.createElement("li");
var id = parseInt(this.id); // retrieve the id of the button
li2.appendChild(document.createTextNode(input2.value));
ul2.appendChild(li2);
knap.push(arr_items[id]); //use the id of the button to select array to push to knap from the array item
console.log(knap);
}
<div>
<input id="userinput" type="number" placeholder="Enter Capacity">
<button id="enter">Enter</button>
</div><br>
<div>
<p>Items Information:</p>
<input id="itemName" type="text" placeholder="enter item name">
<input id="itemWeight" type="number" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" placeholder="enter item value">
<button onclick="addValues()" id="value">Enter</button>
</div>
<ul id="list">LIST OF 20 ITEMS TO CHOOSE FROM
</ul>
<ul id="knap"> LIST OF ITEMS IN KNAPSACK
</ul>
<div>
I believe that should work as you expected
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)
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.
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/