Can't remove local storage elements - javascript

I have a simple to do application with local storage. In my app user can create unordered list with new tasks. Last element in this app is local storage. I have a problem with this functionality.
Before I save the items in localstorage I can delete them using the button. I don't know why but it doesn't works after saving elements.
Any idea how can I fix it?
My code:
const first= document.getElementById("first");
const second= document.getElementById("second");
function addList(e) {
const newElement = document.createElement("li");
newElement.innerHTML = first.value + second.value;
}
newElement.innerHTML += "<button> X </button>";
ul.appendChild(newElement);
store();
newElement.querySelector("button").addEventListener("click", removeElement);
}
function removeElement(e) {
e.target.parentNode.remove();
}
function store() {
window.localStorage.myitems = ul.innerHTML;
}
function getValues() {
let storedValues = window.localStorage.myitems;
if(storedValues) {
ul.innerHTML = storedValues;
ul.querySelector("button").addEventListener("click", removeElement);
}
}
getValues();
<div class="container">
<form>
<input type="text" id="first" name="artist" placeholder="Artist" />
<input type="text" id="second" name="title" placeholder="Song title" />
<button type="button" onclick="addList(event)">Add task</button>
</form>
</div>
<div class="li-elements">
<ul class="list"></ul>
</div>

Looks like you were just missing a few small things in ur code. You were not properly adding the removeElement event listener when loading from localStorage, and you were not properly updating localStorage. I have updated ur code so it works.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div class="container">
<form>
<input type="text" id="first" name="artist" placeholder="Artist" />
<input type="text" id="second" name="title" placeholder="Song title" />
<button type="button" onclick="addList(event)">Add task</button>
</form>
</div>
<div class="li-elements">
<ul id="list" class="list"></ul>
</div>
<script>
function addList(e) {
const first = document.getElementById("first");
const second = document.getElementById("second");
const newElement = document.createElement("li");
newElement.innerHTML = first.value + second.value;
newElement.innerHTML += "<button> X </button>";
document.getElementById("list").appendChild(newElement);
store();
newElement.querySelector("button").addEventListener("click", removeElement);
}
function removeElement(e) {
e.target.parentNode.remove();
store();
}
function store() {
window.localStorage["myitems"] = document.getElementById("list").innerHTML;
}
function getValues() {
let storedValues = window.localStorage["myitems"];
if (storedValues) {
let ul = document.getElementById("list");
ul.innerHTML = storedValues;
for (i = 0; i < ul.childNodes.length; i++) {
ul.childNodes[i].querySelector("button").addEventListener("click", removeElement);
}
}
}
getValues();
</script>
</body>
</html>

Related

JS local storage button coding

hey i need help with creating a delete button for my "notes" so it will delete it from the screen and the localstorage (u will notice i tried to make a delBtn function but with no success) i would appreciate if someone could post a fix to mine and explain me where i went wrong.
My JS
const tableBody = document.getElementById("tableBody");
const taskInfo = document.getElementById("taskInfo");
const taskDate = document.getElementById("taskDate");
const taskTime = document.getElementById("taskTime");
const delBtn = document.getElementById("delBtn")
let x = new Task("this is a test", "2021-04-14", "03:19");
let y = new Task("this is a 2nd test", "2021-04-14", "03:19");
//x.add();
//y.add();
let taskList = [
x, y, (new Task("this is a 3rd test", "2021-04-14", "03:19"))
];
if (localStorage.savedTaskList)
taskList = JSON.parse(localStorage.savedTaskList);
displayTable();
function displayTable() {
tableBody.innerHTML = "";
for (let task of taskList) {
const div = document.createElement("div");
div.setAttribute("class","taskZone");
const divTaskInfo = document.createElement("div");
divTaskInfo.setAttribute("class","taskInfo");
const divTaskDate = document.createElement("div");
divTaskDate.setAttribute("class","taskDate");
const divTaskTime = document.createElement("div");
divTaskTime.setAttribute("class","taskTime");
const delBtn = document.createElement("span");
delBtn.setAttribute("class","delBtn");
divTaskInfo.innerText = task.taskInfo;
divTaskDate.innerText = task.taskDate;
divTaskTime.innerText = task.taskTime;
div.append(divTaskInfo, divTaskDate, divTaskTime);
tableBody.appendChild(div);
}
}
delBtn.onclick = function delTask() {
delBtn.parentNode.removeChild(taskZoneElmToDel)
}
function addTask() {
if (taskInfo.value == '' || taskDate.value == '' || taskTime.value == '') {
return alert(`Please fill all the fields.`);
}else{newTask = new Task(taskInfo.value, taskDate.value, taskTime.value);
taskList.push(newTask);
localStorage.savedTaskList = JSON.stringify(taskList);
displayTable();
}
}
Thats the Html part of it
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Task Board</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
<div class="scaleable-wrapper" id="scaleable-wrapper">
<div class="very-specific-design" id="very-specific-design">
<header class="Title">
My Task Board
</header>
<div id="Input">
</br>
</br>
<form class="Form" id="formInfo">
<label for="taskInfo">Task Info:</label>
<input type="text" id="taskInfo" name="taskInfo" required autofocus></input></br>
<label for="taskDate">Task Date:</label>
<input type="date" id="taskDate" name="taskDate" required></input></br>
<label for="taskTime">Task Time:</label>
<input type="time" id="taskTime" name="taskTime" required></input></br>
<input type="submit" id="addTaskDiv" class="btn" value="Save" onclick="addTask()"></input>
<input type="reset" id="resetForm" class="btn"></input>
</form>
</br>
</br>
</div>
<div class="outNotes"></div>
<div class="tableBody">
<table>
<tbody id="tableBody">
</tbody>
</table>
</div>
</div>
</div>
<input type="button" id="delBtn">x</input>
</body>
<script src="Task.js"></script>
<script src="script2.js"></script>
</html>

My Submit Button does not save text from textarea

I have got problem with my button. Button is not save my text from textarea, and i do not know why.
I everything is conneted and a text shoud go properly to save.
I try look for some typo.
Console in Chrome does not show any mistakes.
I try check for some typo, but i do not find any.
terminal in VisualCode do not show any mistakes
let todoList = null;
let todoForm = null;
let todoSearch = null;
document.addEventListener('DOMContentLoaded', function() {
todoList = document.querySelector('#todoList');
todoForm = document.querySelector('#todoForm');
todoSearch = document.querySelector('#todoSearch');
todoForm.addEventListener('submit', function(e) {
e.preventDefault();
const textarea = this.querySelector('textarea');
if (textarea.value !== ' ') {
addTask(textarea.value);
textarea.value = '';
}
});
});
function addTask(text) {
const todo = document.createElement('div');
todo.classList.add("task-element");
const todoBar = document.createElement('div');
todoBar.classList.add('task-bar');
const todoDate = document.createElement('div');
todoDate.classList.add('task-bar');
const date = new Date();
const dateText = date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getHours() + ':' + date.getMinutes();
todoDate.inner = dateText;
const todoDelete = document.createElement('button');
todoDelete.classList.add('task-delete')
todoDelete.classList.add('button')
todoDelete.innerHTML = '<i class="fas fa-times-circle"></i>';
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
const todoText = document.createElement('div');
todoText.classList.add('task-text');
todoText.innerText = text;
todo.appendChild(todoBar);
todo.appendChild(todoText);
todoList.append(todp);
}
document.addEventListener('DOMContentLoaded', function() {
todoList.addEventListener('click', function(e) {
console.log(e.target)
});
});
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="todo-cnt">
<form class="formquest" id="todoForm">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
</form>
</div>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
<section class="list-cnt">
<header class="header-list">
<h2 class="text-list">
Lista Zadań
</h2>
<form class="list-form">
<input type="search" id="todoSearch" class="search-form">
</form>
</header>
</section>
<div class="task-element">
<div class="task-bar">
<h3 class="task-date">60-80-2019 11:87</h3>
<button class="task-delete" title="Usuń zadanie">
<i class="task-time"></i>
</div>
<div class="task-text" id="todoList">
<p>Przykładowy tekst zadan dla tasku</p>
</div>
</div>
<link rel="stylesheet"type="text/css"href="projekt2.css">
<script src="projekt2.js" async defer></script>
</body>
</html>
Button outside the form
other button not closed
form closed wrongly half inside a div anyway
Spelling of todp instead of todo
I added text to the <i> because I did not load the fontawesome
let todoList = null;
let todoForm = null;
let todoSearch = null;
document.addEventListener('DOMContentLoaded', function() {
todoList = document.querySelector('#todoList');
todoForm = document.querySelector('#todoForm');
todoSearch = document.querySelector('#todoSearch');
todoForm.addEventListener('submit', function(e) {
e.preventDefault();
const textarea = this.querySelector('textarea');
if (textarea.value !== ' ') {
addTask(textarea.value);
textarea.value = '';
}
});
});
function addTask(text) {
const todo = document.createElement('div');
todo.classList.add("task-element");
const todoBar = document.createElement('div');
todoBar.classList.add('task-bar');
const todoDate = document.createElement('div');
todoDate.classList.add('task-bar');
const date = new Date();
const dateText = date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getHours() + ':' + date.getMinutes();
todoDate.inner = dateText;
const todoDelete = document.createElement('button');
todoDelete.classList.add('task-delete')
todoDelete.classList.add('button')
todoDelete.innerHTML = '<i class="fas fa-times-circle">°</i>';
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
const todoText = document.createElement('div');
todoText.classList.add('task-text');
todoText.innerText = text;
todo.appendChild(todoBar);
todo.appendChild(todoText);
todoList.append(todo);
}
document.addEventListener('DOMContentLoaded', function() {
todoList.addEventListener('click', function(e) {
console.log(e.target)
});
});
<form class="formquest" id="todoForm">
<div class="todo-cnt">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
</div>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
<section class="list-cnt">
<header class="header-list">
<h2 class="text-list">
Lista Zadań
</h2>
<form class="list-form">
<input type="search" id="todoSearch" class="search-form">
</form>
</header>
</section>
<div class="task-element">
<div class="task-bar">
<h3 class="task-date">60-80-2019 11:87</h3>
<button class="task-delete" title="Usuń zadanie"><i class="task-time">Task time</i></button>
<div class="task-text" id="todoList">
<p>Przykładowy tekst zadan dla tasku</p>
</div>
</div>
</div>
</div>
</form>
A submit button is supposed to be inside the form tag in order to work.
<div class="todo-cnt">
<form class="formquest" id="todoForm">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
</div>
Remember whenever you are dealing with a submit button you must make sure that the submit button is within the form which you are submitting.
<form class="formquest" id="todoForm">
<div class="firstplace">
<label class="form-message" name="message" for="todoMessage"><p>Podaj treść zadania</p></label>
<textarea class="input" id="input" id="todoMessage"></textarea>
</div>
<div class="button-place">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
<section class="list-cnt">

Add elements With innerHTML and onclick event

start = document.forms[0].start,
end = document.forms[0].end,
result = document.getElementById('result'),
btn = document.getElementById('btn'),
selector = document.getElementById('selector'),
i = start.value;
btn.onclick = ()=> {
"use strict";
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>challenge</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="selector.css" />
</head>
<body>
<header>
<h1>challenge 2 </h1>
<h2>Create an HTML select</h2>
</header>
<section id="input">
<div class="container">
<form>
<input type="text" name="start" id="start" >
<input type="text" name="end" id="end">
<button value="generate" id="btn"> generate</button>
</form>
</div>
</section>
<section id="result">
<select name="years" id="selector">
</select>
</section>
<script src="selector.js"></script>
</body>
</html>
It is supposed to create a new <option> for my <select>, but it executes for 1s only, and then every thing disappears.
I tried to print i on the console but even on the console make the results and every thing was gone.
I am sure I did every thing good so what is the solution to make it work here?
The form is being submitted when you click the button.
onload event can be used to set the click event of the button.
Prevent the submit:
<form onsubmit="return false;">
JS:
window.onload = function() {
btn = document.getElementById('btn');
btn.onclick = function() {
start = document.forms[0].start;
end = document.forms[0].end;
result = document.getElementById('result');
selector = document.getElementById('selector');
i = start.value;
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
}
}
start = document.forms[0].start,
end = document.forms[0].end,
result = document.getElementById('result'),
btn = document.getElementById('btn'),
selector = document.getElementById('selector'),
i = start.value;
btn.onclick = ()=> {
'use strict';
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
}
<section id="input">
<div class="container">
<form>
<input type="text" name="start" id="start" >
<input type="text" name="end" id="end">
<button type="button" value="generate" id="btn"> generate</button>
</form>
</div>
</section>
<section id="result">
<select name="years" id="selector">
</select>
</section>
Use type="button" into your button.
as simple example on your code, just add parameter event, and prevent defaults event of form submit, you can also change the type of
<button value="generate" id="btn" type='button'> generate</button>
btn.onclick = (event)=> {
"use strict";
for (i; i < end.value ; i++) {
selector.innerHTML += '<option>' + i + '</option>';
}
event.preventDefault();
}
If you are trying to add a new option to the select use the "appendChild()" function:
var form = document.getElementByTagName("form")[0];
var btn = document.getElementById('btn');
//To avoid refresh the page when the form is submited.
form.addEventListener("click", function(e){e.preventDefault()},false);
btn.onclick = () => {
var result = document.getElementById('selector'),
var option= document.createElement("option");
option.innerHTML = "some text";
result.appendChild(option);
}
This wild add a new option in the select each time you click the add button

Writing single JS script for assigning ID's to output in HTML

I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>

there are two html pages. I want the data status of first pages to saved when I reverting from next page to first page

When I click on back button of next page the check box value should not be reset.
It should be same as I checked or unchecked. The code from the first and next page is below.
First Page
<!DOCTYPE html>
<html>
<body>
<form>
<input type="checkbox" name="code" value="ECE">ECE<br>
<input type="checkbox" name="code" value="CSE">CSE<br>
<input type="checkbox" name="code" value="ISE">ISE<br>
<br>
<input type="button" onclick="dropFunction()" value="save">
<br><br>
<script>
function dropFunction() {
var branch = document.getElementsByName("code");
var out = "";
for (var i = 0; i < branch.length; i++) {
if (branch[i].checked == true) {
out = out + branch[i].value + " ";
window.location.href="next.html";
}
}
}
</script>
</form>
</body>
</html>
Next Page
<html>
<head>
<title>Welcome to </title>
</head>
<body color="yellow" text="blue">
<h1>welcome to page</h1>
<h2>here we go </h2>
<p> hello everybody<br></p>
</body>
<image src="D:\images.jpg" width="300" height="200"><br>
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.location.href="first.html";
}
</script>
</body>
</html>
Full solution: example. First add ids to your checkboxes:
<input type="checkbox" name="code" value="ECE" id='1'>ECE<br>
<input type="checkbox" name="code" value="CSE" id='2'>CSE<br>
<input type="checkbox" name="code" value="ISE" id='3'>ISE<br>
<input id="spy" style="visibility:hidden"/>
Then change your dropFunction:
function dropFunction() {
var branch = document.getElementsByName("code");
var out = "";
localStorage.clear();
for (var i = 0; i < branch.length; i++)
if (branch[i].checked == true)
localStorage.setItem(branch[i].id, true);
for (var i = 0; i < branch.length; i++) {
if (branch[i].checked == true) {
out = out + branch[i].value + " ";
window.location.href="next.html";
}
}
}
And add some new javascript code to first.html:
window.onload = function() {
var spy = document.getElementById("spy");
if(spy.value=='visited')
for(var i=1;i<=3;i++)
if(localStorage.getItem(i))
document.getElementById(i).checked=true;
spy.value = 'visited';
}

Categories