Trying to delete todo list but not working - javascript

var inputItem = document.getElementById("inputItem");
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
var deleteButton = document.createElement("button");
deleteButton.innerText = "delete";
deleteButton.addEventListener("click", function() {
//console.log("Delete");
//var ul=document.getElementById("list");
var listItem = list.children;
for (var i=0; i < listItem.length; i++) {
while(listItem[i] && listItem[i].children[0].checked) {
ul.removeChild(listItem[i]);
}
}
});
var checkBox = document.createElement("input");
checkBox.type = 'checkbox';
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
label.appendChild(checkBox);
label.appendChild(labelText);
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<form onsubmit="return addItem('list', this.inputItem)">
<input type="text" id="inputItem">
<input type="submit">
</form>
<ul id="list">
</ul>
</body>
</html>

So first of all, there are a few little mistakes in the code:
var list = document.getElementById(list); - You're using the list as the parameter, not a string.
while(listItem[i] && listItem[i].children[0].checked) { - Not sure why you're using while here instead of if.
ul.removeChild(listItem[i]); - ul is commented a few lines above.
Besides these, the delete does not work because of the following line:
if(listItem[i] && listItem[i].children[0].checked) {
If you analyze the DOM, the list item contains a <label></label> that contains the input, which means children[0] is not what you expect it to be.
Therefore, fixing the issues mentioned above and replacing the check in the delete callback function with
if(listItem[i] && listItem[i].getElementsByTagName('input')[0].checked) {
list.removeChild(listItem[i]);
}
should be your fix.

Related

How to reload current page without losing added list items?

I'm creating something similar to a to-do-list project, but whenever I refresh the page I lose all the added items, I've tried using:
`
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
`
but still it doesn't work, I may have used it in the wrong place or wrong way. any help please?
here is my full code:
HTML:
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<title>To Do List</title>
</head>
<body>
<section class="section-center">
<form class="todolist-form">
<h3>To Do List!</h3>
<div class="input-button">
<input type="text" id="items-input" placeholder="e.g. eggs" />
<input
type="button"
class="submit-btn"
onclick="addItems()"
value="Submit"
/>
</div>
<div class="added-items">
<ul id="faves"></ul>
</div>
</form>
</section>
<script src="main.js"></script>
</body>
</html>
`
Javascript:
`
function addItems() {
var li = document.createElement("LI");
li.setAttribute("id", "listItem");
var input = document.getElementById("items-input");
li.innerHTML = input.value;
input.value = "";
document.getElementById("faves").appendChild(li);
var deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "Delete";
deleteBtn.type = "button";
document.getElementById("faves").appendChild(deleteBtn);
var hrzBreak = document.createElement("br");
document.getElementById("faves").appendChild(hrzBreak);
/*********/
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
}
`
What am I doing wrong? I've included jQuery's CDN too, but still it doesn't work.
var texts = [];
function addItems() {
var input = document.getElementById("items-input");
createElement(input.value)
input.value = "";
}
function createElement(value) {
var li = document.createElement("LI");
li.setAttribute("id", "listItem");
li.innerHTML = value;
document.getElementById("faves").appendChild(li);
var deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "Delete";
deleteBtn.type = "button";
document.getElementById("faves").appendChild(deleteBtn);
var hrzBreak = document.createElement("br");
document.getElementById("faves").appendChild(hrzBreak);
texts.push(value)
}
window.onbeforeunload = function () {
// Store text array in storage
localStorage.setItem("list", JSON.stringify(texts));
};
window.onload = function () {
// get list grom storage
var list = localStorage.getItem("list");
if (list !== null) {
list = JSON.parse(list)
for (let index = 0; index < list.length; index++) {
const element = list[index];
// create your dom element
createElement(element)
}
}
};
Using an Array to manage the data flow. This will do the job but still a mess.
Try adding event listeners once and outside of your function
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list")
};
function addItems() {
...
}
Assuming that $("#listItem").val() will return the data you want, place below block outsite of the addItems() function
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};

Check if username already exists, no ajax or php, just pure js

Here is the code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function submit()
{
var ul = document.getElementById("names");
var name = document.getElementById("name").value;
var i = 0, flag = 0;
var allNames = [];
if (allNames.length == 0)
{
allNames[0] = name;
}
else
{
if (allNames.includes(name))
{
alert("Name already exists.");
return -1;
}
else
{
allNames[i++] = name;
}
}
var li = document.createElement("li");
li.innerHTML = name;
ul.appendChild(li);
document.getElementById("name").value = "";
}
</script>
</head>
<body>
<input type="text" id="name">
<button onclick="submit()">Submit</button>
<div>
<h2>Usernames</h2>
<ul id="names"></ul>
</div>
</body>
</html>
Is there any way to check if a username already exists and therefore block the new entry, only using javascript?
I've tried also moving the initialization of the array outside of the function but it doesn't work that way either...
Yes, just declare the allNames variable outside of your function. You currently create it with an empty array each time you call the submit function.
You also have an issue because your i is set to 0 every time. Just use .push if it is not included (instead of trying to specify the index).
var allNames = [];
function submit() {
var ul = document.getElementById("names");
var name = document.getElementById("name").value;
if (allNames.includes(name)) {
alert("Name already exists.");
return -1;
} else {
allNames.push(name);
}
var li = document.createElement("li");
li.innerHTML = name;
ul.appendChild(li);
document.getElementById("name").value = "";
}
<input type="text" id="name">
<button onclick="submit()">Submit</button>
<div>
<h2>Usernames</h2>
<ul id="names"></ul>
</div>

Added text strings do not show in unordered list

I'm trying to code a small application that lets you dynamically add text strings in an unordered list, but the problem is the strings I pass as input do not show up after clicking the "Invia/Send" button. I have tried with a few solutions from other questions, but none of them worked. Any ideas?
<html>
<head>
<title>Promemoria esercizi</title>
</head>
<body>
<ul id="paragraphList">
</ul>
<form id="paragraphForm">
<br></br>
<textarea id="insertParagraph" rows="5" cols="100"></textarea>
<label>Inserisci il paragrafo:
<input type="radio" id="insertType" name="InsertType" value="last">In fondo
<input type="radio" id="insertType" name="InsertType" value="before">Dietro il paragrafo
<select id="beforeParagraph"></select><br></br>
</label>
<button id="add" onclick="addParagraph(paragraphArray)">Inserisci</button><br></br>
</form>
<script>
var paragraphArray = [];
document.getElementById("paragraphList").innerHTML = paragraphArray;
function addParagraph(paragraphArray){
var text = document.getElementById("insertParagraph").value;
var radio = document.getElementById("insertType");
var selectedInsertType = "";
var ul = document.getElementById("paragraphList");
var sel = document.getElementById("beforeParagraph");
var selectedBeforeParagraph = sel.options[sel.selectedIndex].value;
for(i = 0; i < radio.length; i++){
if(radio[i].checked){
selectedInsertType = radio[i].value;
}
}
if(selectedInsertType = "last"){
paragraphArray.push(text);
}else if(selectedInsertType = "before"){
paragraphArray.splice((selectedBeforeParagraph-1), 0, text);
}
var newChoice = document.createElement("option");
newChoice.value = paragraphArray.length.toString();
newChoice.text = paragraphArray.length.toString();
for(i = 0; i < paragraphArray.length; i++){
var li = document.createElement("li");
li.innerHTML = paragraphArray[i];
}
document.getElementById("paragraphList").innerHTML = paragraphArray;
}
</script>
</body>
</html>
There were a few issues:
A common problem people run into with the button tag is by default, it has a type of 'submit' which will submit the form. There are a few ways to disable this, my preferred method is to set the type as button.
Another issue is you don't have any content in the select box, which was causing an error trying to get the value of a select box with no options that can be selected.
I updated your radios, to use querySelectorAll and look for :checked that way you don't need to create an if statement.
I also removed the paragraphArray from addParagraph() since it is a global variable.
<html>
<head>
<title>Promemoria esercizi</title>
</head>
<body>
<ul id="paragraphList">
</ul>
<form id="paragraphForm">
<br></br>
<textarea id="insertParagraph" rows="5" cols="100"></textarea>
<label>Inserisci il paragrafo:
<input type="radio" id="insertType" name="InsertType" value="last">In fondo
<input type="radio" id="insertType" name="InsertType" value="before">Dietro il paragrafo
<select id="beforeParagraph"></select><br></br>
</label>
<button type="button" id="add" onclick="addParagraph()">Inserisci</button><br></br>
</form>
<script>
var paragraphArray = [];
document.getElementById("paragraphList").innerHTML = paragraphArray;
function addParagraph(){
var text = document.getElementById("insertParagraph").value;
var radio = document.querySelectorAll("#insertType:checked");
var selectedInsertType = "";
var ul = document.getElementById("paragraphList");
var sel = document.querySelector("#beforeParagraph");
var selectedBeforeParagraph = (sel.selectedIndex > -1) ? sel.options[sel.selectedIndex].value : "";
for(i = 0; i < radio.length; i++){
selectedInsertType = radio[i].value;
}
if(selectedInsertType = "last"){
paragraphArray.push(text);
}else if(selectedInsertType = "before"){
paragraphArray.splice((selectedBeforeParagraph-1), 0, text);
}
var newChoice = document.createElement("option");
newChoice.value = paragraphArray.length.toString();
newChoice.text = paragraphArray.length.toString();
for(i = 0; i < paragraphArray.length; i++){
var li = document.createElement("li");
li.innerHTML = paragraphArray[i];
}
document.getElementById("paragraphList").innerHTML = paragraphArray;
}
</script>
</body>
</html>

get info by tag name in Javascript

I need a way to capture all the text fields of unknown quantity and save them as a JSON: I'm pretty comfortable coding but new to web. Is this even the way to do it? thanks!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="myP">
field
<br />
</div>
<button onclick="addField()">add field</button>
<button onclick="captureAllInfo()">Capture</button>
<script>
var whichdiv = 0;
function addField() {
whichdiv = whichdiv + 1;
parentDocument = document.getElementById("myP");
var mydiv = document.createElement("div");
mydiv.id = whichdiv;
var input1 = document.createElement("input");
var label1 = document.createElement("label");
label1.innerHTML = "input label 1 ";
input1.id = "Info1";
var input2 = document.createElement("input");
var label2 = document.createElement("label");
label2.innerHTML = "imput label 2";
input2.id = "Info2";
mydiv.appendChild(label1);
mydiv.appendChild(input1);
mydiv.appendChild(label2);
mydiv.appendChild(input2);
parentDocument.appendChild(mydiv);
}
function captureAllInfo() {
for (var i = 0; i < whichdiv; i++) {
console.log("loopin");
var thisDiv = document.getElementById(i);
console.log(thisDiv.getElementById("Info1").value);
}
}
</script>
</body>
</html>
Really what I would like to do is get those two inputs and then add them to a JSON object like
JSON STRUCTURE as below:
{
"1":
{input1 : "string",
input2: "String"},
"2":
{input1 : "string",
input2: "String"}
"3"...,
"4"...
}
We have a function like this document.querySelectorAll('input').
This will fetch all the input elements that exist in your DOM. And then you can modify them as per your requirement.
Please forgive the bad formatting of my function. I wrote this on my fairphone2. The idea is that I used className for the repeated identifiers. Please also note that purely numeric id tags should be avoided.
<html>
<div id="myP">
field
<br />
</div>
<button onclick="addField()">add field</button>
<button onclick="captureAllInfo()">Capture</button>
<script>
var whichdiv = 0;
function addField() {
whichdiv = whichdiv + 1;
parentDocument = document.getElementById("myP");
var mydiv = document.createElement("div");
mydiv.id = 'd'+whichdiv;
mydiv.className='idiv';
var input1 = document.createElement("input");
var label1 = document.createElement("label");
label1.innerHTML = "input label 1 ";
input1.className = "Info1";
var input2 = document.createElement("input");
var label2 = document.createElement("label");
label2.innerHTML = "input label 2";
input2.className = "Info2";
mydiv.appendChild(label1);
mydiv.appendChild(input1);
mydiv.appendChild(label2);
mydiv.appendChild(input2);
parentDocument.appendChild(mydiv);
}
function qsa(s,o){return [...(o||document).querySelectorAll(s)]}
function captureAllInfo() {var o={};
qsa('.idiv').forEach(d=>{
var c=o[d.id.substr(1)]={};
qsa('input',d).forEach(t=>c[t.className]=t.value);
});
console.log(JSON.stringify(o));
}
</script>
</html>
Edit:.
I added the shortcut function qsa() for the various "QuerySelectorAll" methods to make everything a bit more readable. qsa() returns an Array instead of a simple nodelist. The second argument in qsa() is optional. If given it will be the element for which the .querySelectorAll() method will be called. It defaults to document.

Displayed lists by JS

I want to see three different lists depending on which one I choose. The problem is that when I want to display the second one, the first one does not disappear (I used remove() ). May someone help? And the second question is, is there an easier way to create li in ul with JS? My code is overcomplicate I guess. *I'm beginner with JS btw.
function showList()
{
var games = document.getElementById("games").checked; // true;false
var movies = document.getElementById("movies").checked; // true;false
var series = document.getElementById("series").checked; // true;false
if(games == true)
{
var exists = document.getElementsByTagName("ul");
if (exists == true)
{
exists.remove();
}
var ul = document.createElement('ul');
var li = document.createElement("LI");
var content1 = document.createTextNode("Witcher");
li.appendChild(content1);
ul.appendChild(li);
document.getElementById('box_list').appendChild(ul);
var li2 = document.createElement("LI");
var content2 = document.createTextNode("GTA V");
li2.appendChild(content2);
ul.appendChild(li2);
document.getElementById('box_list').appendChild(ul);
}
if(movies == true)
{
var exists = document.getElementsByTagName("ul");
if (exists == true)
{
exists.remove();
}
var ul = document.createElement('ul');
var li = document.createElement("LI");
var content1 = document.createTextNode("Matrix");
li.appendChild(content1);
ul.appendChild(li);
document.getElementById('box_list').appendChild(ul);
var li2 = document.createElement("LI");
var content2 = document.createTextNode("The Lord of The Rings");
li2.appendChild(content2);
ul.appendChild(li2);
document.getElementById('box_list').appendChild(ul);
}
if(series == true)
{
var exists = document.getElementsByTagName("ul");
if (exists == true)
{
exists.remove();
}
var ul = document.createElement('ul');
var li = document.createElement("LI");
var content1 = document.createTextNode("Game of Throne");
li.appendChild(content1);
ul.appendChild(li);
document.getElementById('box_list').appendChild(ul);
var li2 = document.createElement("LI");
var content2 = document.createTextNode("The Walking Dead");
li2.appendChild(content2);
ul.appendChild(li2);
document.getElementById('box_list').appendChild(ul);
}
}
<input type="radio" name="list" id="games" onclick="showList()"/> Game <br/>
<input type="radio" name="list" id="movies" onclick="showList()"/> Movies <br/>
<input type="radio" name="list" id="series" onclick="showList()"/> Series <br/>
<p id="box_list">
</p>
your code is a bit messy. Try to use functions with few lines, they will be more readable. Also try to avoid the onclick event inside HTML because it's a bad practice (check online why). Finally use variables instead of calling document every time. For your problem I created this solution:
var games = document.getElementById('games');
var movies = document.getElementById('movies');
var series = document.getElementById('series');
var boxList = document.getElementById('box_list');
games.addEventListener('click', () => addToList('a','b'));
movies.addEventListener('click', () => addToList('c','d'));
series.addEventListener('click', () => addToList('e','f'));
function addToList(...names){
let ul = document.createElement('ul');
for(let name of names){
let li = document.createElement("li");
let content = document.createTextNode(name);
li.appendChild(content);
ul.appendChild(li);
}
boxList.innerHTML = '';
boxList.appendChild(ul);
}
<input type="radio" name="list" id="games" /> Game <br/>
<input type="radio" name="list" id="movies"/> Movies <br/>
<input type="radio" name="list" id="series"/> Series <br/>
<p id="box_list">
</p>
If you are unfamiliar with javascript, the ...names is called spread operator and it's useful when you have to cycle a list of object (in this case some strings)
I did some edit, you can use this as an html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<input type="radio" name="list" id="games" onclick="showList()" /> Game
<br />
<input type="radio" name="list" id="movies" onclick="showList()" /> Movies
<br />
<input type="radio" name="list" id="series" onclick="showList()" /> Series
<br />
<p id="box_list"></p>
<script type="text/javascript">
function showList() {
var games = document.getElementById("games").checked; // true;false
var movies = document.getElementById("movies").checked; // true;false
var series = document.getElementById("series").checked; // true;false
if (games == true) {
var elem = document.querySelector("ul");
elem && elem.parentNode.removeChild(elem);
var ul = document.createElement("ul");
var li = document.createElement("LI");
li.innerHTML = "Witcher";
ul.appendChild(li);
document.getElementById("box_list").appendChild(ul);
var li2 = document.createElement("LI");
li2.innerHTML = "GTA V";
ul.appendChild(li2);
document.getElementById("box_list").appendChild(ul);
}
if (movies == true) {
var elem = document.querySelector("ul");
elem && elem.parentNode.removeChild(elem);
var ul = document.createElement("ul");
var li = document.createElement("LI");
li.innerHTML = "Matrix";
ul.appendChild(li);
document.getElementById("box_list").appendChild(ul);
var li2 = document.createElement("LI");
li2.innerHTML = "The Lord of The Rings";
ul.appendChild(li2);
document.getElementById("box_list").appendChild(ul);
}
if (series == true) {
var elem = document.querySelector("ul");
elem && elem.parentNode.removeChild(elem);
var ul = document.createElement("ul");
var li = document.createElement("LI");
li.innerHTML = "Game of Throne";
ul.appendChild(li);
document.getElementById("box_list").appendChild(ul);
var li2 = document.createElement("LI");
li2.innerHTML = "The Walking Dead";
ul.appendChild(li2);
document.getElementById("box_list").appendChild(ul);
}
}
</script>
</body>
</html>

Categories

Resources