Displayed lists by JS - javascript

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>

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");
};

Trying to delete todo list but not working

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.

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>

Cannot remove list item from ul todo list

I tried to remove the list item inside ul with querySelectorAll and remove going through each li element. Where is the mistake please, and how is it fixed?
<div class='container'>
<h1> New todo list</h1>
<form>
<input type= 'text' id='item'
required>
<ul> </ul>
<button id='button'> clear all</
button>
</div>
Here's the code:
var form =
document.querySelector('form')
var ul = document.querySelector('ul')
var button =
document.querySelector(#button)
var input =
document.querySelector('item')
var liMaker = text => {
var li =
document.createElement('li')
li.textContent = text
ul.insertBefore(li,
ul.childNodes[0])
button.onclick = remove
}
form.addEventListener('submit',
function(e){
e.preventDefault()
liMaker(input.value)
input.value = ' '
})
function remove(e){
Array.from(
document.querySelectorAll('
li')).forEach(item =>
e.target.item.remove())
}
I have edited your code a little and added a new button to keep the functionality separate. I think this is the kind of functionality you were after if I understood your question correctly.
<div class='container'>
<h1> New todo list</h1>
<form>
<input type='text' id='item' required>
<ul id="myList"></ul>
<button id='button'>add</button>
</form>
<button id="clear">Clear</button>
</div>
JS:
var form = document.querySelector('form')
var ul = document.querySelector('ul')
var button = document.querySelector('#button');
var input = document.querySelector('#item');
var clear = document.querySelector('#clear');
var liMaker = text => {
var li = document.createElement('li');
li.textContent = text;
ul.insertBefore(li, ul.childNodes[0])
}
form.addEventListener('submit', function(e) {
e.preventDefault()
liMaker(input.value)
input.value = '';
});
clear.addEventListener('click', remove);
function remove(){
saveToDos();
while (ul.firstChild) {
ul.removeChild(ul.firstChild);
}
}
function saveToDos() {
var items = ul.getElementsByTagName("li");
for (var i = 0; i < items.length; ++i) {
savedToDos.push(items[i].innerHTML);
}
localStorage.setItem('savedValues', savedToDos);
}
Here is a link to a working pen: https://codepen.io/caeking/pen/RzyKmV

Deleting last item on the list

I have a simple HTML unordered list and a JavaScript function that adds items at position [0], and another that deletes items at [0] as well, but what can I add to the delete function (strictly basic JavaScript please even if it's longer) so it deletes the last added item? Thank you in advance:
HTML:
<html>
<body>
<h1> Shopping List </h1>
<button onclick="adding()"> Add </button>
<input type="text" id="input" placeholder="Enter Items"> </input>
<button onclick="remove()"> Remove Last </button>
<ul id="list">
</ul>
</body>
</html>
Javascript:
function adding() {
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
var newText = document.createTextNode(input);
newEl.appendChild(newText);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
}
function remove() {
var removeEl = document.getElementsByTagName("li")[0];
var containerEl = removeEl.parentNode;
containerEl.removeChild(removeEl);
}
function adding() {
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
var newText = document.createTextNode(input);
newEl.appendChild(newText);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
}
function remove() {
var els = document.getElementsByTagName("li");
var removeEl = els[els.length - 1]; // <-- fetching last el
var containerEl = removeEl.parentNode;
containerEl.removeChild(removeEl);
}
<html>
<h1> Shopping List </h1>
<button onclick="adding()"> Add </button>
<input type="text" id="input" placeholder="Enter Items"> </input>
<button onclick="remove()"> Remove Last </button>
<ul id="list">
</ul>
</body>
</html>
If els is an array, it has indices from 0 to els.length - 1. 0 is the first, els.length - 1 is the last index.
Besides, try not to use attribute event handlers like onclick="adding()". A much better practice is to attach them programmatically, for clean separation of concerns:
<button id="add">Add</button>
and then
document.getElementById('add').addEventListener('click', adding);
Purely speaking this answers the question as it only removes the last added item then won't remove anything else
window.lastadded = false;
function adding() {
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
newEl.id = Date.parse(new Date());
var newText = document.createTextNode(input);
window.lastadded = newEl.id;
newEl.appendChild(newText);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
}
function remove() {
lastElement = document.getElementById(window.lastadded);
lastElement.parentNode.removeChild(lastElement);
}

Categories

Resources