Add arrays of value in object propertie javascript - javascript

I'm trying to read all the values of an attribute my page an get, for each attribute (some attribute can has multiple value separate by comma) the div id
This is my html page:
const elements = document.querySelectorAll('[data-att]');
let obj = {};
elements.forEach(function(element) {
let v = element.getAttribute('data-att');
let id = element.id;
comma = v.includes(",");
if (comma) {
s = v.split(",");
s.forEach(function(single) {
obj[single] = {
id: id
};
});
} else {
obj[v] = {
id: id
};
}
});
console.log(obj);
<!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>
</head>
<body>
<div id="due" data-att="foo"></div>
<div id="uno" data-att="foo"></div>
<div id="tre" data-att="foo,bar"></div>
<div id="quattro" data-att="brum"></div>
<div id="cinque" data-att="foo,brum"></div>
</body>
</html>
What's the problem?
At the moment i needed to assign the attrbute id using obj[single] = {id: id}; cause i tried to make a obj[single].push(id); but I get error
Anyone can hel me to reach this resoult:
{
"foo": {
['due','uno','tre','cinque']
},
"bar": {
['tre']
},
"brum": {
['cinque']
}
}

I think this is what you need:
const elements = document.querySelectorAll('[data-att]');
let obj = {};
elements.forEach(el => {
const keys = el.dataset.att.split(',');
keys.forEach(key => {
if(obj[key] === undefined){
obj[key] = [];
}
obj[key].push(el.id)
})
})
console.log(obj);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<div id="due" data-att="foo"></div>
<div id="uno" data-att="foo"></div>
<div id="tre" data-att="foo,bar"></div>
<div id="quattro" data-att="brum"></div>
<div id="cinque" data-att="foo,brum"></div>
</body>
</html>
The result is not the same you posted, i think you made a mistake there, or was it me? :)

Check if the property already exists. If it does, push onto the array, otherwise create the array.
There's no need for if (comma). Splitting a string with no comma will return an array with a single element, you can loop over this with forEach().
const elements = document.querySelectorAll('[data-att]');
let obj = {};
elements.forEach(function(element) {
let v = element.getAttribute('data-att');
let id = element.id;
s = v.split(",");
s.forEach(function(single) {
if (obj[single]) {
obj[single].push(id);
} else {
obj[single] = [id];
}
});
});
console.log(obj);
<!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>
</head>
<body>
<div id="due" data-att="foo"></div>
<div id="uno" data-att="foo"></div>
<div id="tre" data-att="foo,bar"></div>
<div id="quattro" data-att="brum"></div>
<div id="cinque" data-att="foo,brum"></div>
</body>
</html>

Related

Remove listing after being entered

I want to make a website so that it will randomly generate a number. I want to be able to type in the number in a input box, press submit, and have the matching generated number removed from the list.
**I want to only use HTML and Javascript if possible
I tried to look online
A simple implementation is this. You can further develop as you wish.
<!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>
</head>
<body>
<div id="result"></div>
<button type="number" id="get">Get random number</button>
<div id="arr">
</div>
<button type="number" id="rm">Remove number <span id="rnumber"></span></button>
<script>
let arr = [0,1,2,3,4,5,6,7,8,9];
let n;
document.getElementById("get").addEventListener("click", getRandomInt);
document.getElementById("arr").innerHTML = arr;
document.getElementById("rm").addEventListener("click", rmNumber);
function getRandomInt() {
n = Math.floor(Math.random() * 10);
document.getElementById("result").innerHTML = n;
}
function rmNumber() {
let n = Number(document.getElementById("result").childNodes[0].textContent);
arr = arr.filter(i => i != n);
document.getElementById("arr").innerHTML = arr;
}
</script>
</body>
</html>

Get my HTML to activate the JS, and be able to select information from my array

I have made an array with 3 names, and i basically want it so, if someone types in one of the names in the array, i want it to show an alert box, well basically showing that the JS is doing something.
Cheers Guys.
var names = ['Alex', 'Dale', 'Mike'];
var nameSelector = document.getElementById('name-area').value;
function nameGrabber() {
if (nameSelector === names[0]) {
alert("Nice Name bro.");
} else if (nameSelector === names[1]) {
alert("Mate, that's a name that you have.");
} else if (nameSelector === names[3]) {
alert("Ok that's fine.");
} else {
alert("PUT IN ONE OF THE NAMES PLEAZE... thanks :)");
}
}
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Javascript Lesson</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="app.js"></script>
</head>
<body>
<input type="text" id="name-area"></input>
<input type="submit" onclick="nameGrabber()"></input>
</body>
</html>
You need to move the nameSelector variable into your submit function, otherwise the value of nameSelector always remains the initial value of the input field (which is empty). Something like:
var names = ['Alex', 'Dale', 'Mike'];
function nameGrabber() {
var nameSelector = document.getElementById('name-area').value;
if (nameSelector === names[0]) {
alert("Nice Name bro.");
} else if (nameSelector === names[1]) {
alert("Mate, that's a name that you have.");
} else if (nameSelector === names[3]) {
alert("Ok that's fine.");
} else {
alert("PUT IN ONE OF THE NAMES PLEAZE... thanks :)");
}
}
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Javascript Lesson</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="app.js"></script>
</head>
<body>
<input type="text" id="name-area"></input>
<input type="submit" onclick="nameGrabber()"></input>
</body>
</html>

values from input box is not saving on localstorage

i have develop a todo app. where user insert some values and it gets save on the screen. now i want to save the values into localstorage.but its not getting saved instead i am getting a empty {}.
here is the javascript code
//crete element from input box and delete
let knoo = document.getElementById('kno')
let box= document.getElementById('txt')
let sub= document.getElementById('sub').addEventListener('click',()=>{
let para = document.createElement('ul')
para.innerText= box.value
knoo.appendChild(para)
box.value=''
localStorage.setItem('key', JSON.stringify(para))
//styling
para.addEventListener('click', ()=>{
para.style.textDecoration = 'line-through'
})
//delete
para.addEventListener('dblclick', ()=>{
knoo.removeChild(para)
})
})
here is the 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">
<title>Document</title>
</head>
<body>
<h2>hi</h2>
<div id="hello">
<h1>hello</h1>
</div>
<button id="btn">delete</button> <br>
<br>
<input type="text" id="txt">
<button type="submit" id="sub">+</button>
<div id="kno"></div>
<script src="main.js"></script>
</body>
</html>
That is because you use JSON.stringify with a html element which will not work and it will always produce {}.
The JSON.stringify() method converts a JavaScript object or value to a JSON string
I solution is to use array to store the value for para and use JSON.stringify for the array
let knoo = document.getElementById('kno')
let box= document.getElementById('txt')
let storedvalue = []
if(localStorage.getItem('key')){
storedvalue = localStorage.getItem('key');
}
let sub= document.getElementById('sub').addEventListener('click',()=>{
let para = document.createElement('ul')
para.innerText= box.value
knoo.appendChild(para)
box.value=''
storedvalue.push(para.innerText)
localStorage.setItem('key', JSON.stringify(storedvalue))
//styling
para.addEventListener('click', ()=>{
para.style.textDecoration = 'line-through'
})
//delete
para.addEventListener('dblclick', ()=>{
knoo.removeChild(para)
})
})
<!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>
</head>
<body>
<h2>hi</h2>
<div id="hello">
<h1>hello</h1>
</div>
<button id="btn">delete</button> <br>
<br>
<input type="text" id="txt">
<button type="submit" id="sub">+</button>
<div id="kno"></div>
<script src="main.js"></script>
</body>
</html>

Cannot set property of undefined error on button press

I'm trying to change the background color of a div element on button press but I'm getting the error Cannot set property 'BackgroundColor' of undefined. The event handler for the button is inside the window.onload event. I thought at that point every element inside the html document would be loaded, but apparently not.
Here is the code:
<!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>
</head>
<body>
<div class="random">This should become unreadable</div>
<button id="button">Click me!</button>
<script>
window.onload = function() {
document.getElementById("button").addEventListener('click', function() {
document.getElementsByClassName("random").style.BackgroundColor= "black";
});
}
</script>
</body>
</html>
try the following code segment.
the issue is document.getElementsByClassName("random") returning an array of elements.So you should select one element from that array and get the style of that element.
And BackgroundColor should be backgroundColor
<!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>
</head>
<body>
<div class="random">This should become unreadable</div>
<button id="button">Click me!</button>
<script>
window.onload = function() {
document.getElementById("button").addEventListener('click', function() {
document.getElementsByClassName("random")[0].style.backgroundColor= "black";
});
}
</script>
</body>
</html>
You can this out - getElementsByClassName produces error "undefined"
Another alternative could be this.
<body>
<div id="random">This should become unreadable</div>
<button id="button">Click me!</button>
<script>
window.onload = function() {
document.getElementById("button").addEventListener('click', function() {
document.getElementById("random").style.backgroundColor= "black";
});
}
</script>
Modify the script as follows and try again:
<!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>
</head>
<body>
<div class="random">This should become unreadable</div>
<button id="button">Click me!</button>
<script>
window.onload = function() {
document.getElementById("button").addEventListener('click', function() {
document.querySelector(".random").style.backgroundColor= "black";
});
}
</script>
</body>
</html>
Look into comments by #Bravo, document.getElementsByClassName("random") returns a HTMLCollection, not a single element - therefore document.getElementsByClassName("random").style is undefined
<!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>
</head>
<body>
<div class="random">This should become unreadable</div>
<button id="button">Click me!</button>
<script>
window.onload = function () {
document
.getElementById('button')
.addEventListener('click', function () {
const button = document.getElementsByClassName('random');
for (let index = 0; index < button.length; index++) {
const element = button[index];
element.style.backgroundColor = 'black';
}
// if you will have only one element with class=random or if you only want to apply style to the first element with class=random, then
// button[0].style.backgroundColor = 'black';
// in your case, you should add an id to the element and use id as the selector
});
};
</script>
</body>
</html>

Random number generator in textarea [duplicate]

This question already has answers here:
How to change the Content of a <textarea> with JavaScript
(6 answers)
Closed 2 years ago.
How can add the following JavaScript code (a random number generator)?
function randomNumber(max) {
return Math.floor(Math.random() * max + 1);
}
const list = []
while(list.length < 25) {
let nbr = randomNumber(25)
if(!list.find(el => el === nbr))
list.push(nbr)
}
console.log("list",list)
into this textarea and displaying them with DOM?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<textarea name="" id="" cols="30" rows="10"></textarea>
<script src="app.js"></script>
</body>
</html>
// Using an id to get the element
const textarea = document.getElementById('area');
function randomNumber(max) {
return Math.floor(Math.random() * max + 1);
}
const list = []
while(list.length < 25 ){
let nbr = randomNumber(25)
if(!list.find(el => el === nbr))
list.push(nbr)
}
// Set the value to the list
textarea.value = list;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<textarea name="" id="area" cols="30" rows="10"></textarea>
<script src="app.js"></script>
</body>
</html>

Categories