Function creates unwanted copy of an array as an element of itself - javascript

Basically, I have a function that creates N input fields based on user choice, then I want to get those inputs for processing later on, though for some reason it creates a copy of the return over and over again, unless I add something like "conj.pop()" in the return. I wouldn't like to work not knowing why it only works if I pop the last one.
I put a console.log to keep track and the returned array was something like this:
Array(3)
0: 'A'
1: 'B'
2: (3) ['A','B','Array(3)]
If you expand this last array it repeats infinitely this very same description.
OBS: The inputs I've been using were simple 2,2 and A B, C D.
OBS2: The code wasn't previously in english so I translated some stuff, and left other small ones as they were variables only.
document.getElementById("ok1").onclick = () => {
const esp_qtd = document.getElementById("esp_qtd").value;
const car_qtd = document.getElementById("car_qtd").value;
document.getElementById("parte1").classList.add("invisivel");
document.getElementById("parte2").classList.remove("invisivel");
console.log(esp_qtd, car_qtd);
const generateFields = (tipo) => {
const qtd = document.getElementById(tipo + "_qtd").value;
const parent = document.getElementById(tipo + "_lista");
for (let i = 0; i < qtd; i++) {
const input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("id", (tipo + i));
parent.appendChild(input);
if (qtd > 5) {
if (((i + 1) % 3) == 0) parent.appendChild(document.createElement("br"));
}
console.log(i);
}
}
generateFields("esp");
generateFields("car");
const inputFields = (tipo, conj) => {
const qtd = document.getElementById(tipo + "_qtd").value;
for (let i = 0; i < qtd; i++) {
conj[i] = document.getElementById(tipo + i).value;
console.log("Iteration: " + i, conj);
}
return conj;
}
document.getElementById("ok2").onclick = () => {
const conjE = [];
const conjC = [];
conjE.push(inputFields("esp", conjE));
conjC.push(inputFields("car", conjC));
console.log(conjE);
console.log(conjC);
}
}
* {
font-family: 'Roboto', sans-serif;
font-size: 14pt;
margin-top: 1rem;
}
.invisivel {
display: none;
}
label {
margin-top: 1rem;
}
input {
margin-top: 0.5rem;
margin-right: 1rem;
margin-bottom: 0.5rem;
}
button {
margin-top: 1rem;
}
<!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">
<title>DOC</title>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
</head>
<body>
<div class="container">
<!-- PART 1 -->
<div id="parte1">
<form>
<label>N1</label><br>
<input type="text" id="esp_qtd"><br>
<label>N2</label><br>
<input type="text" id="car_qtd"><br>
<button id="ok1" type="button">OK</button>
</form>
</div>
<!-- PART 2 -->
<div id="parte2" class="invisivel">
<div id="esp_lista">
<label>ELEMENTS 1</label><br>
</div>
<div id="car_lista">
<label>ELEMENTS 2</label><br>
</div>
<button id="ok2" type="button">OK</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>

Please change your JS as follows:
document.getElementById("ok1").onclick = () => {
const esp_qtd = document.getElementById("esp_qtd").value;
const car_qtd = document.getElementById("car_qtd").value;
document.getElementById("parte1").classList.add("invisivel");
document.getElementById("parte2").classList.remove("invisivel");
console.log(esp_qtd, car_qtd);
const generateFields = (tipo) => {
const qtd = document.getElementById(tipo + "_qtd").value;
const parent = document.getElementById(tipo + "_lista");
for (let i = 0; i < qtd; i++) {
const input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("id", tipo + i);
parent.appendChild(input);
if (qtd > 5) {
if ((i + 1) % 3 == 0) parent.appendChild(document.createElement("br"));
}
console.log(i);
}
};
generateFields("esp");
generateFields("car");
const inputFields = (tipo, conj) => {
const qtd = document.getElementById(tipo + "_qtd").value;
console.log("Conj:" + qtd);
for (let i = 0; i < qtd; i++) {
conj[i] = document.getElementById(tipo + i).value;
console.log("Iteration: " + i, conj);
}
return conj;
};
document.getElementById("ok2").onclick = () => {
const conjE = [];
const conjC = [];
inputFields("esp", conjE);
inputFields("car", conjC);
console.log(conjE);
console.log(conjC);
};
};
I have only removed conjE.push() and conjC.push().
Explanation:
You are passing an array to store your data in it. But you're also returning the same array and storing it in it again. This creates an infinite loop of values. Either pass the variable or return the list.

Related

List element getAttribute("value") returns wrong values after calling another function (swapping elements)

I am still learning Javascript and don't understand why I get wrong values when calling getAttribute('data-value') from removeButton after swapping elements with swapping() function.
const addButton = document.querySelector('.addButton');
const swapButton = document.querySelector('.swapButton');
var input = document.querySelector('.input');
const draggable_list = document.getElementById('draggable-list');
let items;
const array = [];
const listItems = [];
let dragStartIndex;
class item {
constructor(itemName) {
this.createDiv(itemName);
}
createDiv(itemName) {
let input = document.createElement('input');
input.value = itemName;
input.disabled = true;
input.classList.add('item_input');
input.type = 'text';
let removeButton = document.createElement('button');
removeButton.innerHTML = 'REMOVE';
removeButton.classList.add('removeButton');
draggable_list.appendChild(items);
items.appendChild(removeButton);
removeButton.addEventListener('click', (event) => {
let itemNumber = event.target.closest('li').getAttribute('data-value');
console.log("The deleted number has a value of: ", itemNumber); //returns wrong 'data-value' numbers
if (event && event.target.parentElement) {
this.remove(event.target.parentElement, input.value);
}
});
}
//Remove numbers
remove(item, value) {
draggable_list.removeChild(item);
//delete from array
let indexArray = array.indexOf(value);
array.splice(indexArray,1);
//delete from listItems
listItems.splice(indexArray,1);
//redfine indexes of li elements after deletion
array.forEach((numbers,index) => {
items.setAttribute('data-index', index);
items.setAttribute('data-value', numbers);
} );
}
}
//Create numbers
async function create() {
if (input.value != '') {
array.push(input.value);
array.forEach((numbers,index) => {
//if numbers already exists in the UI, then pass?
items = document.createElement('li');
items.setAttribute('data-index', index);
items.setAttribute('data-value', numbers);
items.innerHTML = `
<div class="draggable" draggable="true">
<p class="phone-number" id="div">${numbers}</p>
<i class="fas fa-grip-lines"></i>
</div>`;
} );
listItems.push(items); //used for swapping
new item(input.value);
input.value = ''
}
}
// Swap list items
function swapItems(fromIndex, toIndex) {
const itemOne = listItems[fromIndex].querySelector('.draggable');
const itemTwo = listItems[toIndex].querySelector('.draggable');
//swap UI items
listItems[fromIndex].appendChild(itemTwo);
listItems[toIndex].appendChild(itemOne);
//swap array items
[array[fromIndex], array[toIndex]] = [array[toIndex], array[fromIndex]];
console.log("This is array after swapping: ",array);
//redefine li index and values
array.forEach((numbers,index) => {
items.setAttribute('data-index', index);
items.setAttribute('data-value', numbers);
console.log("The values of the numbers aftwer swapping are: ", numbers); //'data-value' numbers are correct here
} )
}
function swapping(){
const draggables = document.querySelectorAll('.draggable');
const dragListItems = document.querySelectorAll('.draggable-list li');
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', dragStart);
});
dragListItems.forEach(item => {
item.addEventListener('dragover', dragOver);
item.addEventListener('drop', dragDrop);
});
}
function dragStart() {
dragStartIndex = +this.closest('li').getAttribute('data-index');
}
function dragOver(e) {
e.preventDefault();
}
function dragDrop() {
const dragEndIndex = +this.getAttribute('data-index');
swapItems(dragStartIndex, dragEndIndex);
}
addButton.addEventListener('click', create);
swapButton.addEventListener('click', swapping);
<!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">
<title>Document</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/4690c1252a.js" crossorigin="anonymous"></script>
</head>
<body>
<h1><span class="styling">Add a number</span> </h1>
<div class="input_div">
<input type="text" class="input" placeholder="Add Task" />
<button class="addButton">+</button>
<button class="swapButton">SWAP</button>
</div>
<ul class="draggable-list" id="draggable-list"></ul>
<script src="code.js"></script>
</body>
</html>
If I try inserting the numbers 1, 2, 3 for example, I swap 1 with 2. Then delete 1, itemNumber will have a vlue of 2 instead of 1. Why is that?
const addButton = document.querySelector('.addButton');
const swapButton = document.querySelector('.swapButton');
var input = document.querySelector('.input');
const draggable_list = document.getElementById('draggable-list');
let items;
const array = [];
const listItems = [];
let dragStartIndex;
class item {
constructor(itemName) {
this.createDiv(itemName);
}
createDiv(itemName) {
let input = document.createElement('input');
input.value = itemName;
input.disabled = true;
input.classList.add('item_input');
input.type = 'text';
let removeButton = document.createElement('button');
removeButton.innerHTML = 'REMOVE';
removeButton.classList.add('removeButton');
draggable_list.appendChild(items);
items.appendChild(removeButton);
removeButton.addEventListener('click', (event) => {
let itemNumber = event.target.closest('li').dataset.value;
console.log("The deleted number has a value of: ", itemNumber);
if (event && event.target.parentElement) {
this.remove(event.target.parentElement, itemNumber);
}
});
}
//Remove numbers
remove(item, value) {
draggable_list.removeChild(item);
//delete from array
let indexArray = array.indexOf(value);
array.splice(indexArray, 1);
//delete from listItems
listItems.splice(indexArray, 1);
//redfine indexes of li elements after deletion
array.forEach((numbers, index) => {
draggable_list.children[index].dataset.index = index;
draggable_list.children[index].dataset.value = numbers;
});
}
}
//Create numbers
async function create() {
if (input.value != '') {
array.push(input.value);
array.forEach((numbers, index) => {
//if numbers already exists in the UI, then pass?
items = document.createElement('li');
items.dataset.index = index;
items.dataset.value = numbers;
items.innerHTML = `
<div class="draggable" draggable="true">
<p class="phone-number" id="div">${numbers}</p>
<i class="fas fa-grip-lines"></i>
</div>`;
});
listItems.push(items); //used for swapping
new item(input.value);
input.value = ''
}
}
// Swap list items
function swapItems(fromIndex, toIndex) {
const itemOne = listItems[fromIndex].querySelector('.draggable');
const itemTwo = listItems[toIndex].querySelector('.draggable');
//swap UI items
listItems[fromIndex].prepend(itemTwo);
listItems[toIndex].prepend(itemOne);
//swap array items
[array[fromIndex], array[toIndex]] = [array[toIndex], array[fromIndex]];
console.log("This is array after swapping: ", array);
//redefine li index and values
array.forEach((numbers, index) => {
draggable_list.children[index].dataset.index = index;
draggable_list.children[index].dataset.value = numbers;
console.log("The values of the numbers after swapping are: ", numbers);
})
}
function swapping() {
const draggables = document.querySelectorAll('.draggable');
const dragListItems = document.querySelectorAll('.draggable-list li');
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', dragStart);
});
dragListItems.forEach(item => {
item.addEventListener('dragover', dragOver);
item.addEventListener('drop', dragDrop);
});
}
function dragStart() {
dragStartIndex = +this.closest('li').dataset.index;
}
function dragOver(e) {
e.preventDefault();
}
function dragDrop() {
const dragEndIndex = +this.dataset.index;
swapItems(dragStartIndex, dragEndIndex);
}
addButton.addEventListener('click', create);
swapButton.addEventListener('click', swapping);
<!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">
<title>Document</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/4690c1252a.js" crossorigin="anonymous"></script>
</head>
<body>
<h1><span class="styling">Add a number</span> </h1>
<div class="input_div">
<input type="text" class="input" placeholder="Add Task" />
<button class="addButton">+</button>
<button class="swapButton">SWAP</button>
</div>
<ul class="draggable-list" id="draggable-list"></ul>
<script src="code.js"></script>
</body>
</html>

How to change the loop to reverse the square print in Javascript

I'm learning java script and I'm currently working with testing in javiscritp, I've done this code that you can look at, but I don't know how to reverse now the order of these cubes to be 2 up and 1 down (see what I want in the picture) I know I need to change something for loops but I fail in any way to get what I want.
let Tabela = (function () {
const dajRed = function (tabela) {
let red = document.createElement("tr");
tabela.appendChild(red);
return red;
}
const dajCeliju = function (red, prikazi) {
let celija = document.createElement("td");
if (!prikazi) celija.style = "display:none;";
red.appendChild(celija)
return celija;
}
const crtaj = function (x, y) {
const body = document.getElementsByTagName("body")[0];
let tabelaEl = document.createElement("table");
body.appendChild(tabelaEl);
for (let i = 0; i < y; i++) {
let red = dajRed(tabelaEl);
for (let j = 0; j < x; j++) {
dajCeliju(red, j < i);
}
}
}
return {
crtaj: crtaj
}
}());
//table.crtaj(3,3)
//i=0 ⍉⍉⍉
//i=1 ⎕⍉⍉
//i=2 ⎕⎕⍉
//Tabela.crtaj(8, 8);
let assert = chai.assert;
describe('Tabela', function() {
describe('crtaj()', function() {
it('should draw 3 rows when parameter are 2,3', function() {
Tabela.crtaj(2,3);
let tabele = document.getElementsByTagName("table");
let tabela = tabele[tabele.length-1]
let redovi = tabela.getElementsByTagName("tr");
assert.equal(redovi.length, 3,"Broj redova treba biti 3");
});
it('should draw 2 columns in row 2 when parameter are 2,3', function() {
Tabela.crtaj(2,3);
let tabele = document.getElementsByTagName("table");
let tabela = tabele[tabele.length-1]
let redovi = tabela.getElementsByTagName("tr");
let kolone = redovi[2].getElementsByTagName("td");
let brojPrikazanih = 0;
for(let i=0;i<kolone.length;i++){
let stil = window.getComputedStyle(kolone[i])
if(stil.display!=='none') brojPrikazanih++;
}
assert.equal(brojPrikazanih, 2,"Broj kolona treba biti 2");
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Mocha Tests</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
<style>
td{
border: 1px solid black;
height: 20px;
width: 20px;
}
</style>
</head>
<body>
<div id="ispis"></div>
<div id="mocha"></div>
<script src="https://unpkg.com/chai/chai.js"></script>
<script src="https://unpkg.com/mocha/mocha.js"></script>
<script class="mocha-init">
mocha.setup('bdd');
mocha.checkLeaks();
</script>
<script src="tabela.js"></script>
<script src="test.js"></script>
<script class="mocha-exec">
mocha.run();
</script>
</body>
</html>
Invert the check in dajCeliju:
if (prikazi) celija.style = "display:none;";
OR second option - change the params:
dajCeliju(red, j >= i);
Is this what you need?

Insert Process into Queue to work Asynchronously

I am trying to make a simple web page in which when we enter the text value in the textbox, and as soon as a user inserts a comma between the two texts, a new button gets generated. When the user presses the enter key, the buttons class should toggle between warning and danger.
I am able to achieve it so I also tried to add a delay, but the problem is all buttons class toggling takes place together and not one by one in a random manner. To create a random toggling sequence I created a random permutation of numbers for it, but since all buttons classes are toggling simultaneously I am not getting the required result.
The required result is that first for one buttons toggling should be completed and then for another button - how can I achieve this?
let element = document.querySelector('.textarea');
let cont = document.querySelector('.groupofbtns');
let lastlen = 0;
const pause = (timeoutMsec) => new Promise(resolve => setTimeout(resolve, timeoutMsec))
async function main(grp) {
// here is the delay I am trying to create between toggling but it is executing for all buttons simultaneously.
grp.classList.remove("btn-warning");
grp.classList.add("btn-danger");
await pause(3 * 1000)
grp.classList.remove("btn-danger");
grp.classList.add("btn-warning");
}
element.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
let grp = document.querySelectorAll('.btn')
let l = grp.length - 1, arr = [];
console.log(grp.length)
do {
let num = Math.floor(Math.random() * l + 1);
arr.push(num);
arr = arr.filter((item, index) => {
return arr.indexOf(item) === index
});
} while (arr.length < l);
// console.log(arr);
arr.push(0)
for (let i = 0; i <= l; i++) {
main(grp[arr[i]])
}
}
else if (event.keyCode === 8) {
let val = element.value;
//console.log(val)
let strArr = val.split(',')
let b, f;
let grp = document.querySelectorAll('.btn');
if (strArr.length > 1) {
b = strArr;
while (b[b.length - 1] == "")
b.pop()
if (b.length < strArr.length) {
cont.removeChild(grp[grp.length - 1]);
lastlen--;
}
f = b[b.length - 1];
}
if (grp.length == b.length)
grp[grp.length - 1].innerText = `${f}`;
else {
let diff = grp.length - b.length
let i = 0;
while (diff > 0) {
cont.removeChild(grp[grp.length - 1 - i]);
i++;
diff--;
lastlen--;
}
}
}
});
element.addEventListener('input', function (event) {
let val = element.value;
//console.log(val)
let strArr = val.split(',')
let b, f;
if (strArr.length > 1) {
b = strArr;
while (b[b.length - 1] == "")
b.pop()
f = b[b.length - 1];
if (event.keyCode !== 8) {
if (strArr.length > lastlen) {
let butt = document.createElement('button');
butt.classList.add('btn')
butt.classList.add('btn-warning')
//butt.classList.add('container')
butt.classList.add('active')
butt.innerText = `${f}`
cont.appendChild(butt)
lastlen = strArr.length
//cont.innerHTML += `<button type="button" class="btns" >${f}</button>`;
}//element.value = val;
else {
let b = document.querySelectorAll('.btn')
b[b.length - 1].innerText = `${f}`
}
}
}
})
.h
{
display:flex;
flex-direction: column;
width: 50%;
margin-top:30%;
align-items: center;
text-align: center;
}
.lab
{
color:white;
}
.btn
{
margin: 0.8% 0.8%;
}
.groupofbtns
{
width:50%;
margin-top: 2%;
align-items: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Random color picker</title>
<link rel="stylesheet" href="randomcolorcss.css">
</head>
<body style="background-color: blue;">
<div class="container h">
<div class="input-group">
<label for="text" class="lab">Enter your choices here separate them with
commas, Press
Enter when you are
done</label>
<br>
<textarea cols="5" rows="5" class=" textarea form-control" placeholder="Enter Choices here" name="text"
style="width: fit-content; display: block;"></textarea>
</div>
</div>
<div class="groupofbtns container">
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js"
integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s"
crossorigin="anonymous"></script>
<script src="randomcolor.js"></script>
</body>
</html>

how to delete card and index of array when a remove button clicked?

Hello I want to delete the whole card and the data in index of array when the remove button clicked.
I show it to you in this photo.
here is my code :
var list;
function setData() {
for (var i = 0; i < list.length; i++) {
var card = document.createElement("li");
var img = document.createElement("img");
var cardBody = document.createElement("div");
var cardTitle = document.createElement("h4");
var cardText = document.createElement("p");
var submit = document.createElement("a");
var remove = document.createElement("a");
card.className = "card col-md-3 col-sm-4";
cardBody.className = "card-body";
img.className = "card-img-top";
cardTitle.className = "card-title";
cardText.className = "card-text";
submit.className = "btn btn-primary stretched-link";
remove.className = "btn btn-danger stretched-link";
img.src = list[i].avatar;
cardTitle.append(document.createTextNode(list[i].first_name + list[i].last_name));
cardText.append(document.createTextNode(list[i].email));
submit.append(document.createTextNode("submit"));
remove.append(document.createTextNode("remove"));
cardBody.appendChild(cardTitle);
cardBody.appendChild(cardText);
cardBody.appendChild(submit);
cardBody.appendChild(remove);
card.appendChild(img);
card.appendChild(cardBody);
$("#list").append(card);
}
}
$(document).ready(function () {
$.ajax({
url: "https://reqres.in/api/users",
type: "get",
contentType: "application/json",
headers: {
"Access-Control-Allow-Origin": "*",
},
success: function (data) {
list = data.data;
console.log(list);
setData();
},
error: function (request, status, errorThrown) {
console.log("error", +status + errorThrown);
},
});
});
.card {
width: 100%;
margin-bottom: 5px;
}
img {
width: 100%;
}
a {
margin: 5px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>GETTING STARTED WITH BRACKETS</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<ul class="row" id="list">
</ul>
</body>
</html>
I want to remove the index of the date in list when user clicked in the remove button on that index and then call setdate();
thanks a lot I am new in web development.
You require a click event for your delete button:
remove.addEventListener('click', function(ev) {
var btn = ev.target
var cardBody = btn.parentElement
var card = cardBody.parentElement
card.parentElement.removeChild(card)
setData()
})
Or with ES6 arrow functions () => {}, which preserves the scope where the function was created in:
remove.addEventListener('click', (ev) => {
card // from your creating function
card.parentElement.removeChild(card)
setData()
})
just before $("#list").append(card) add a click event to the card like this :
card.addEventListener('click',(event)=>{
if(event.terget.innerText === 'remove'){
card.remove()
}
})
Assuming that your list variable is a global variable, If you want to resue the setData function. Please
do it in the below way,
add the remove function for removing data in list.
function removeData(index) {
// index starts from 0
let tempList = [];
for (var i = 0; i < list.length; i++) {
if (i != index)
tempList.push(list[index]);
}
list = tempList;
setData();}
Now,
function setData() {
$("#list").empty();
// add eventlistener to remove tag to call the removeDataFunction, rest all code remains the same
for (var i = 0; i < list.length; i++) {
var card = document.createElement("li");
var img = document.createElement("img");
.
.
.
.
.
remove.addEventListener('click', removeData(i))
$("#list").append(card);
}}}

Button for each item in localstorage

How to add button for each item in localstorage to remove that item?
I have code for setItem and getItem from localstorage, but I don't know how I can add a button or x for each item to remove it.
2020-03-01 March x
2020-04-01 April x
It looks like add item to card or remove item from card.
plz help me
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#inpkey").datepicker();
});
</script>
<style>
fieldset{
margin-bottom:20px;
}
input{
padding: 7px;
height:40px;
}
</style>
</head>
<body>
<fieldset>
<input type="text" id="inpkey" placeholder="Click and select date">
<input type="text" id="inpvalue">
<button type="button" id="btninsert">Save</button>
</fieldset>
<fieldset>
<div id="output"></div>
</fieldset>
<script>
const inpkey = document.getElementById("inpkey");
const inpavv = document.getElementById("inpvalue");
const spara = document.getElementById("btninsert");
const output = document.getElementById("output");
spara.onclick = function () {
const key = inpkey.value;
const value = inpavv.value;
console.log(key);
console.log(value);
if (key && value ) {
localStorage.setItem(key, value );
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
console.log(localStorage.getItem(key));
output.innerHTML += `${key}:&nbsp&nbsp&nbsp&nbsp ${value} <p />`;
}
</script>
</body>
</html>
Something like this: Note JSFiddle had trouble removing the last element. Might be something I overlooked in the code. Good luck.
const setup = () => {
const spara = document.querySelector('#btninsert');
const output = document.querySelector('#output');
spara.addEventListener('click', addMyEntry);
output.addEventListener('click', removeMyEntry);
insertEntries(output);
};
const insertEntries = (target) => target.insertAdjacentHTML('beforeend', loadEntryHTML());
const loadEntryHTML = () => {
let html = '';
if(localStorage.length !== 0) {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
html += createEntryHTML(key, value);
}
}
return html;
};
const createEntryHTML = (key, value) => `<p><label class="lbl_key">${key}:</label><span class="sp_value">${value}</span> remove<p/>`;
const addMyEntry = () => {
const inpkey = document.querySelector('#inpkey');
const inpavv = document.querySelector('#inpvalue');
const key = inpkey.value;
const value = inpavv.value;
if (key && value ) {
localStorage.setItem(key, value );
const output = document.querySelector('#output');
output.insertAdjacentHTML('beforeend', createEntryHTML(key, value));
}
};
const removeMyEntry = (event) => {
const target = event.target;
if(target.nodeName === 'A') {
event.currentTarget.removeChild(target.parentNode);
localStorage.removeItem(target.dataset.key);
}
};
//load
window.addEventListener('load', setup);
.lbl_key {
padding-right: 1em;
}
<fieldset>
<input type="text" id="inpkey" placeholder="Click and select date">
<input type="text" id="inpvalue">
<button type="button" id="btninsert">Save</button>
</fieldset>
<fieldset>
<div id="output"></div>
</fieldset>
A better solution to build elements dynamically.
const app = document.getElementById("app");
const localStorage = [1, 2, 3, 4];
for (let index = 0; index < localStorage.length; index++) {
// const key = localStorage.key(index);
// const value = localStorage.getItem(key);
let div = document.createElement("div");
div.className = "cart_item";
div.id = "cart_item_" + index;
div.textContent = localStorage[index] + new Date().toUTCString() + "";
let cross = document.createElement("span");
cross.className = "cross";
cross.textContent = " X";
cross.addEventListener("click", function remove() {
alert("Remove item");
});
div.appendChild(cross);
app.appendChild(div);
}
<!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>Static Template</title>
<link rel="stylesheet" href="app.css" />
<!-- <script src="https://deepak-proxy-server.herokuapp.com/https://gist.githubusercontent.com/deepakshrma/4b6a0a31b4582d6418ec4f76b7439781/raw/e7377474ce9e411b4d8de4b10f4437a24774c0e2/Mapper.js"></script> -->
<style>
.cart_item{
border: 1px solid;
padding: 20px 40px;
}
.cross {
color: red;
cursor: pointer;
}
</style>
</head>
<body>
<div id="app">
</div>
</body>
</html>

Categories