Why doesn't my js code clear the input field - javascript

I'm trying to clear my input field in my simplified to-do list but I can't get my code to clear the input when I add a new task.
If you look in the JS code you can see a simple code (input.value = "";) to clear the input but it doesn't work. Also the IF function that is supposed to have an alert message if you don't put any text in the input field doesn't work for some reason either.
I don't really understand how I can get them to work, I've been looking on W3 but can't find any good answers.
<h2>To-do list!</h2>
<div>
<input type="text" id="task" placeholder="Write task" />
<button id="my-button">Add task</button>
</div>
<ul id="list"></ul>
var btn = document.getElementById('my-button').onclick = function() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var input = document.getElementById('task').value;
if (input != '') {
addItem();
}
function createDeleteButton() {
var deleteButton = document.createElement('button');
deleteButton.classList.add("deleteButton");
deleteButton.textContent = "x";
deleteButton.addEventListener("click", removeItem);
return deleteButton;
}
function addItem() {
let listElement = document.createElement('li');
listElement.innerText = input;
listElement.appendChild(createDeleteButton());
if (input.value != "") {
list.appendChild(listElement)
} else
alert("Please write something");
input.value = "";
}
function removeItem() {
let parent = this.parentNode.parentNode;
let child = this.parentNode;
parent.removeChild(child);
}
}

There are some problems with your code.
You are wrapping all the functions inside add button onClick function. No need to do that, it make things complicated.
You are first checking if input is empty, so when addItem function executes, the inner if else will never be executed:
} else alert("Please write something");
How to do it?
1 Declare the elements you want to use:
const ul = document.getElementById("list");
const input = document.getElementById("task");
const addBtn = document.getElementById("my-button");
2 Make your add button's onClick function to do only what it have to do: add an item.
addBtn.onclick = addItem;
3 Declare the addItem function:
function addItem() {
if (input.value !== "") {
const listElement = document.createElement("li");
listElement.innerText = input.value;
listElement.appendChild(createDeleteButton());
ul.appendChild(listElement);
input.value = "";
} else {
alert("Please write something");
}
}
The addItem function first checks if input value is empty, and if it is not empty, do everything in the block. Else execute the else block (alert).
Note that at the end of the if block we set input's value to empty with : input.value = "";
Declare the createDeleteButton and removeItem functions.
I don't change them because they work. Just have them all outside of addItem function and use const instead of var (scope reasons).
function createDeleteButton() {
const deleteButton = document.createElement("button");
deleteButton.classList.add("deleteButton");
deleteButton.textContent = "x";
deleteButton.addEventListener("click", removeItem);
return deleteButton;
}
function removeItem() {
const parent = this.parentNode.parentNode;
const child = this.parentNode;
parent.removeChild(child);
}
Here is the full code:
======================
const ul = document.getElementById("list");
const input = document.getElementById("task");
const addBtn = document.getElementById("my-button");
addBtn.onclick = addItem;
function addItem() {
if (input.value !== "") {
const listElement = document.createElement("li");
listElement.innerText = input.value;
listElement.appendChild(createDeleteButton());
ul.appendChild(listElement);
input.value = "";
} else {
alert("Please write something");
}
}
function createDeleteButton() {
const deleteButton = document.createElement("button");
deleteButton.classList.add("deleteButton");
deleteButton.textContent = "x";
deleteButton.addEventListener("click", removeItem);
return deleteButton;
}
function removeItem() {
const parent = this.parentNode.parentNode;
const child = this.parentNode;
parent.removeChild(child);
}

var input is defined as task.value. You need to get task and then change task.value
function todolist(){
var btn = document.getElementById('my-button').onclick = function() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var input = document.getElementById('task').value;
if (input != '') {
addItem();
}
function createDeleteButton() {
var deleteButton = document.createElement('button');
deleteButton.classList.add("deleteButton");
deleteButton.textContent = "x";
deleteButton.addEventListener("click", removeItem);
return deleteButton;
}
function addItem() {
let listElement = document.createElement('li');
listElement.innerText = input;
listElement.appendChild(createDeleteButton());
if (input != "") {
list.appendChild(listElement)
} else alert("Please write something");
var task = document.getElementById('task')
console.log(task)
task.value = ""
input = "";
}
function removeItem() {
let parent = this.parentNode.parentNode;
let child = this.parentNode;
parent.removeChild(child);
}
}
}
todolist();
<h2>To-do list!</h2>
<div>
<input type="text" id="task" placeholder="Write task" />
<button id="my-button">Add task</button>
</div>
<ul id="list"></ul>

Instead of input.value = "" use input = ""

Related

Local storage in JS not loading items problem

I have a problem with the local storage it seems the items are getting saved to local storage but I cannot make it work to load at start.
Any tips and advice much appreciated.
I am posting the code below.
const input = document.getElementById('input');
const list = document.getElementById('list');
const addButton = document.getElementById('addButton');
const completed = document.getElementById("completed");
let LIST;
let id;
let loadSTORAGE = localStorage.getItem("STORAGE");
if (loadSTORAGE) {
LIST = JSON.parse(loadSTORAGE);
id = LIST.length;
loadList(LIST);
} else {
LIST = [];
id = 0;
}
function loadList() {
LIST.forEach(function() {
addTask();
});
}
addButton.addEventListener("click", addTask);
input.addEventListener("keyup", function(event) {
(event.keyCode === 13 ? addTask() : null)
})
function addTask() {
const newTask = document.createElement("li");
const delBtn = document.createElement("button");
const checkBtn = document.createElement("button");
delBtn.innerHTML = "<button>Reset</button>"
checkBtn.innerHTML = "<button>Done</button>"
if (input.value !== "") {
newTask.textContent = input.value;
list.appendChild(newTask);
newTask.appendChild(checkBtn);
newTask.appendChild(delBtn);
LIST.push({
name: input.value,
id: id,
});
id++
input.value = "";
console.log(LIST);
localStorage.setItem("STORAGE", JSON.stringify(LIST));
}
checkBtn.addEventListener("click", function() {
const parent = this.parentNode
parent.remove();
completed.appendChild(parent);
});
delBtn.addEventListener("click", function() {
const parent = this.parentNode
parent.remove();
});
}
You need to break out the logic of building the item and getting the value. Something like the following where the addTask just makes sure there is input and calls a method that builds an item. Now with the localstorage call, you can call just the code that builds the item.
const input = document.getElementById('input');
const list = document.getElementById('list');
const addButton = document.getElementById('addButton');
const completed = document.getElementById("completed");
const loadSTORAGE = localStorage.getItem("STORAGE");
const LIST = loadSTORAGE ? JSON.parse(loadSTORAGE) : [];
let id = LIST.length;
loadList(LIST);
function loadList() {
LIST.forEach(function(data) {
addTaskElement(data);
});
}
function addTask() {
if (input.value !== "") {
cons newItem = {
name: input.value,
id: id,
};
LIST.push(newItem);
id++;
localStorage.setItem("STORAGE", JSON.stringify(LIST));
input.value = "";
addTaskElement(newItem);
}
}
function addTaskElement(data) {
const newTask = document.createElement("li");
const delBtn = document.createElement("button");
const checkBtn = document.createElement("button");
delBtn.textContent = "Reset"
checkBtn.textContent = "Done"
newTask.textContent = data.name;
newTask.appendChild(checkBtn);
newTask.appendChild(delBtn);
list.appendChild(newTask);
}

Issue with local storage for to-do list

I'm trying to add local storage to my to-do list. While refreshing the page does maintain the list item, the value comes back as undefined. I suspect it's something to do with the lack of an argument when I call the addInput function at the bottom, but I can't see a way around it.
In addition, if the toggled checked class is on and the item is crossed out, is there a way to store the class information?
I'd very much appreciate any help you can give me.
The offending code is below:
https://codepen.io/david-webb/pen/yLeqydK
function saveTodos () {
let jsonstr = JSON.stringify(todos);
localStorage.setItem('todos', jsonstr);
}
function getTodos () {
localStorage.getItem('todoList')
let jsonstr = localStorage.getItem("todos");
todos = JSON.parse(jsonstr);
if (!todos) {
todos = [];
}
}
//cross out text on click
document.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
saveTodos ();
}
});
getTodos ();
addInput ();
Try this please:
<input type="text" style="font-size:25px;" id="input" placeholder="Write here">
<button id="addBtn">Add item</button>
<ul id="myUL">
</ul>
<script>
let todo = [];
document.getElementById('addBtn').addEventListener('click', function () {
let value = document.getElementById('input').value;
if (value) {
todo.push(value);
saveTodos()
addInput(value);
}
});
function addInput(text) {
//add list item on click
let listItem = document.createElement('li');
let list = document.getElementById('myUL');
let input = document.getElementById('input').value;
let textNode = document.createTextNode(text);
//create and append remove button
let removeBtn = document.createElement("BUTTON");
list.appendChild(removeBtn);
removeBtn.className = "removeBtn";
removeBtn.innerHTML = "Remove item";
listItem.appendChild(removeBtn);
list.appendChild(listItem);
listItem.appendChild(textNode);
document.getElementById("input").value = "";
removeBtn.addEventListener('click', removeItem);
//console.log(todo);
}
//remove list item on click
function removeItem() {
let item = this.parentNode.parentNode;
let parent = item.parentNode;
let id = parent.id;
let value = parent.innerText;
todo.splice(todo.indexOf(value, 1));
saveTodos();
this.parentNode.parentNode.removeChild(this.parentNode);
console.log(todo)
}
function saveTodos() {
let jsonstr = JSON.stringify(todo);
localStorage.setItem('todos', jsonstr);
}
function getTodos() {
localStorage.getItem('todos')
let jsonstr = localStorage.getItem("todos");
todos = JSON.parse(jsonstr);
if (todos && !todos.length) {
todos = [];
}
else{
if(todos){
for(var intCounter = 0; intCounter < todos.length; intCounter++){
addInput(todos[intCounter]);
}
}
}
}
//cross out text on click
document.addEventListener('click', function (ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
saveTodos();
}
});
getTodos();
// addInput();
</script>
Call addInput within the getTodos function so that as soon as you're done with retreiving the list you print it.
This is what I changed:
function getTodos
function getTodos() {
localStorage.getItem('todos')
let jsonstr = localStorage.getItem("todos");
todos = JSON.parse(jsonstr);
if (todos && !todos.length) {
todos = [];
}
else{
if(todos){
for(var intCounter = 0; intCounter < todos.length; intCounter++){
addInput(todos[intCounter]);
}
}
}
}
Commented addInput().

how to loop through each list and add local stored item in it

I have a Bookmark Page where I add edit and delete bookmarks. and I have stored these items in localStorage. the issue is in loaddata function where I get the stored data and save it back in newly created li. the li tag is storing all the inputs that I typed in just one list. what I want is each bookmark should be within its own list just like additem function. but I don't know how to achieve this
const search = document.querySelector('form input');
const input = document.querySelector('.add-text');
const container = document.querySelector('ul');
let items = null;
let currentItem = null;
let array = [];
const searchItems = function(e) {
if (items) {
let word = e.target.value.toLowerCase();
for (let item of items) {
if (item.firstChild.textContent.toLowerCase().indexOf(word) !== -1) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
}
}
}
const deleteItem = function(e) {
currentItem = null;
e.target.parentNode.remove();
input.value = '';
}
const editItem = function(e) {
currentItem = e.target.parentNode.firstChild;
input.value = currentItem.textContent;
}
const updateItem = function(e) {
if (currentItem) {
currentItem.textContent = input.value;
input.value = '';
}else{
alert('No Selected Text Here to Update');
return;
}
}
const addItem = function() {
let val = input.value;
if (val) {
let li = document.createElement('li');
let inner = '<h1 class="text">' + val + '</h1>';
inner += '<button class="delete">Delete</button>';
inner += '<button class="edit">Edit</button>';
array.push(inner);
let stringified = JSON.stringify(array);
localStorage.setItem('list', stringified);
li.innerHTML = inner;
container.appendChild(li);
input.value = '';
currentItem = li.firstChild;
items = document.querySelectorAll('li');
for (let del of document.querySelectorAll('.delete')) {
del.addEventListener('click', deleteItem);
}
for (let edit of document.querySelectorAll('.edit')) {
edit.addEventListener('click', editItem);
}
} else {
alert('please add some text');
return;
}
}
function loaddata(){
let li = document.createElement('li');
let stringified = localStorage.getItem('list');
let listitems = JSON.parse(stringified);
li.innerHTML = listitems;
container.appendChild(li);
console.log(li);
}
loaddata();
search.addEventListener('keyup', searchItems);
document.querySelector('#add').addEventListener('click', addItem);
document.querySelector('#update').addEventListener('click', updateItem);
Considering your list is an array, you need to loop through it and create adn populate elements within that loop. Try to edit your loaddata function this way:
// Mock content
let container = document.body
localStorage.setItem('list', JSON.stringify(['<h1>Foo</h1>', '<h1>Bar</h1>', '<h1>Baz</h1>']))
loaddata()
// Edited 'loaddata'
function loaddata() {
let stringified = localStorage.getItem('list');
console.log(stringified)
let listitems = JSON.parse(stringified);
for (let i = 0; i < listitems.length; i++) {
let li = document.createElement('li');
li.innerHTML = listitems[i];
container.appendChild(li);
console.log(li);
}
}
It can't be run like a code snippet in Stack Overflow sandbox due to security reasons (accessing Local Storage), so if you want to test it, consider copying to JSFiddle or so.

How do I get the input validation to see if user input already exists in the table?

Thank you for looking at this problem. I am trying to get the input value validated by not allowing it to store when it is found in the table. I am struggling to find the variable that it stores as so that i can put that in the validation.
This is my code:
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '' || inputValue === ) {
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
I am trying to put my validation in the IF statement.
Ypu need to add another method before newElement like below.
var eleExist = function(eleValue){
var lis = document.getElementById("myUL").getElementsByTagName("li");
return lis.find(x => x.value.toLowerCase() === eleValue.toLowerCase());
}
ANd then
function newElement() {
....
....
var inputValue = document.getElementById("myInput").value;
if (inputValue === '' || eleExist(inputValue) ) {
alert("You must write something!");
}
}
Something like above should work. Note i didn't try hence you may have to do a little test.
For memory efficient but not time efficient way, you can add a function to validate and call it inside the if statement:
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === ''|| notDuplicated(inputValue) ) {
alert("You must write something and you cannot add the same place
twice!");
} else {
document.getElementById("myUL").appendChild(li);
}
// etc...
}
//add this
function notDuplicated (text) {
//list of all previously entered values
var list = document.getElementById("myUL").getElementsByTagName("li");;
for (var item of list) {
if (item.value === text) {
//text value already inserted before
return true;
}
}
//this means the value was not entered before
return false
}
Or the way i prefere For time efficient but not memory efficient way, easily you can store the values inside an object -more use of memory but you can skip adding a new function for validation-:
//make sure this one is global not inside the function
window.insertedTexts = {};
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
//check if we have it in our new object
if (inputValue === ''|| window.insertedTexts[inputValue] ) {
alert("You must write something and you cannot add the same place
twice!");
} else {
//and add each new value to the object you created
window.insertedTexts[inputValue] = true;
document.getElementById("myUL").appendChild(li);
}
// etc...
}
Use the jQuery .each() method to iterate through all the <li> elements that are inside a parent of id="myUL" to check if the value exists.
I added an example <ul id="myUL"> element to show how it works.
This is the function that changed:
function newElement()
{
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
// if empty
if (inputValue.length == 0)
{
alert("You must write something!");
}
else
{
var exists = false;
// go through all 'li' child elements of parent with id 'myUL'
$( "#myUL li" ).each(function( index )
{
// $( this ).text() is the text of the current 'li' ellement
var currentLiText = $( this ).text();
// search for the appended char, the ×
var doesItContainX = currentLiText.indexOf('\u00D7');
// if an × is found remove it
if (doesItContainX !== false)
{
currentLiText = currentLiText.substr(0, doesItContainX, currentLiText.length);
}
// compare the current li value to the inputValue
// if they are the same, mark that a match was found
if(currentLiText.toLowerCase() == inputValue.toLowerCase()) exists = true;
});
// if we didn't find a match add it
if(!exists)
{
document.getElementById("myUL").appendChild(li);
var t = document.createTextNode(inputValue);
li.appendChild(t);
}
else
{
// we found a match report error
alert('the value already exists');
}
}
Here is the code:
(run the snippet at the bottom)
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement()
{
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
// if empty
if (inputValue.length == 0)
{
alert("You must write something!");
}
else
{
var exists = false;
// go through all 'li' child elements of parent with id 'myUL'
$( "#myUL li" ).each(function( index )
{
// $( this ).text() is the text of the current 'li' ellement
var currentLiText = $( this ).text();
// search for the appended char, the ×
var doesItContainX = currentLiText.indexOf('\u00D7');
// if an × is found remove it
if (doesItContainX !== false)
{
currentLiText = currentLiText.substr(0, doesItContainX, currentLiText.length);
}
// compare the current li value to the inputValue
// if they are the same mark that a match was found
if(currentLiText.toLowerCase() == inputValue.toLowerCase()) exists = true;
// for case-insensitive remove the .toLowerCase()
});
// if we didn't find a match add it
if(!exists)
{
document.getElementById("myUL").appendChild(li);
var t = document.createTextNode(inputValue);
li.appendChild(t);
}
else
{
// we found a match report error
alert('the value already exists');
}
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++)
{
close[i].onclick = function()
{
var div = this.parentElement;
div.style.display = "none";
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myUL">
<li>America</li>
<li>asia</li>
<li>germany</li>
<li>Italy</li>
<li>Canada</li>
</ul>
<input type="text" id="myInput" value="" />
<input type="button" value="click to add element" onclick="newElement()" />

localStorage data does not show when window reloads

I am building a mock-up RSVP app, and I can't get the localStorage data to come up when the page refreshes. I am aiming to be able to insert a name and have the name get appended to the invitation list. Then, the user can either repeat those steps for multiple names or edit the names in the list. I have this part down, but if I were to refresh the page, the invitees are no longer in the list below the input bar. I need it to where it will keep the names in the list, and the buttons on the list items (edit, remove) will still work.
With the 'main code' below, the item is added to the localStorage and set as 'rsvp', but the visible list is not updated until I refresh the page. I need it to update every time I hit the submit button. I have tried adding
if (rsvp != null) {
ul.outerHTML = rsvp;
}
right below
console.log(rsvp);
but when I click submit, the list is not updated and in the console you see the data that was loaded the previous time you used the app.
For example, if I type in 'Test', click submit, type in 'Test2', click submit then type in 'Test3' and click submit again - the list is not visibly updated, you get an error in the console saying 'Uncaught DOMException: Failed to set the 'outerHTML' property on 'Element': This element has no parent node.', and the list is never updated until you refresh the page, type in another name and click submit. Again, if you do this, the list is not updated until you repeat the same process.
Main code (without the rsvp 'if' statement in the handler)
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('registrar');
const input = form.querySelector('input');
const mainDiv = document.querySelector('.main');
const ul = document.getElementById('invitedList');
const div = document.createElement('div');
const filterLabel = document.createElement('label');
const filterCheckbox = document.createElement('input');
filterLabel.textContent = "Hide those who haven't responded";
filterCheckbox.type = 'checkbox';
div.appendChild(filterLabel);
div.appendChild(filterCheckbox);
mainDiv.insertBefore(div, ul);
// Creates the list item for the RSVP list
function createLI(text) {
function createElement(elementName, property, value) {
const element = document.createElement(elementName);
element[property] = value;
return element;
}
function appendToLI(elementName, property, value) {
const element = createElement(elementName, property, value);
li.appendChild(element);
return element;
}
const li = document.createElement('li');
appendToLI('span', 'textContent', text);
appendToLI('label','textContent', 'Confirm')
.appendChild(createElement('input', 'type', 'checkbox'));
appendToLI('button', 'textContent', 'edit');
appendToLI('button', 'textContent', 'remove');
return li;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
const text = input.value;
input.value = '';
// Checks for empty string in the input area
if (text === '') {
alert("You have not entered a name, please try again.");
return;
}
// Checks for duplicate names
for (i = 0; i < ul.children.length; i++) {
if (text === ul.children[i].children[0].textContent) {
alert("This name has already been entered. Please enter a different name.");
return;
}
}
const li = createLI(text);
ul.appendChild(li);
localStorage.setItem('rsvp', JSON.stringify(ul.outerHTML));
});
const rsvp = JSON.parse(localStorage.getItem('rsvp'));
if (rsvp != null) {
ul.outerHTML = rsvp;
}
// Changes list item from confirm to confirmed
ul.addEventListener('change', (e) => {
const checkbox = event.target;
const checked = checkbox.checked;
const label = checkbox.parentNode;
const listItem = checkbox.parentNode.parentNode;
if (checked) {
listItem.className = 'responded';
label.childNodes[0].textContent = 'Confirmed';
} else {
listItem.className = '';
label.childNodes[0].textContent = 'Confirm';
}
});
ul.addEventListener('click', (e) => {
if (e.target.tagName === 'BUTTON') {
const button = e.target;
const li = button.parentNode;
const ul = li.parentNode;
const action = button.textContent;
const nameActions = {
remove: () => {
ul.removeChild(li);
},
edit: () => {
const span = li.firstElementChild;
const input = document.createElement('input');
input.type = 'text';
input.value = span.textContent;
li.insertBefore(input, span);
li.removeChild(span);
button.textContent = 'save';
},
save: () => {
const input = li.firstElementChild;
const span = document.createElement('span');
span.textContent = input.value;
li.insertBefore(span, input);
li.removeChild(input);
button.textContent = 'edit';
}
};
// select and run action in button's name
nameActions[action]();
}
});
// Filters out those who have not yet responded
filterCheckbox.addEventListener('change', (e) => {
const isChecked = e.target.checked;
const lis = ul.children;
if (isChecked) {
for (let i = 0; i < lis.length; i++) {
let li = lis[i];
if (li.className === 'responded') {
li.style.display = '';
} else {
li.style.display = 'none';
}
}
} else {
for (let i = 0; i < lis.length; i++) {
let li = lis[i];
li.style.display = '';
}
}
});
});
const rsvp = JSON.parse(localStorage.getItem('rsvp'))
is called within DOMContentLoaded event handler
if (rsvp != null) {
ul.outerHTML = rsvp;
}
is called immediately following .addEventListener(); also the code at Question does not indicate where localStorage.getItem('rsvp') is set before const rsvp = JSON.parse(localStorage.getItem('rsvp')) is called.
You can check is localStorage has the property key "rsvp" before defining rsvp, and use if condition and statement with DOMContentLoaded event handler.

Categories

Resources