Add JS array values to multiple divs - javascript

I have an array
var arr = [3,0,1,0,0];
and multiple divs.
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>
and more.
How to add values from an array alternately by numbers in an array to div numbers by classes.
<div class="fb0">3</div>
<div class="fb4">0</div>
<div class="fb2">1</div>
<div class="fb3">0</div>
<div class="fb1">0</div>

You can use jQuery's .each() to loop through all the div. Inside event handler function use the index to take the item from the array and set the text of the current element:
var arr = [3,0,1,0,0];
$('[class^=fb]').each(function(idx){
if(arr.length >= idx) // check if the array length is grater/equal to the current index.
$(this).text(arr[idx]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>
JavaScript solution with Document.querySelectorAll() and Array.prototype.forEach():
var arr = [3,0,1,0,0];
var elements = [].slice.call(document.querySelectorAll('[class^=fb]'));
elements.forEach(function(div, idx){
if(arr.length >= idx) // check if the array length is grater/equal to the current index.
div.textContent = arr[idx];
});
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>

You can use querySelectorAll to select the div's and than using forEach you can add the values to each div accordingly.
function update(){
let arr = [3,0,1,0,0];
let divs = document.querySelectorAll('[class^=fb]')
divs.forEach((e,i)=>{
e.innerHTML = arr[i]
})
}
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>
<button onClick=update()>Click me to see output</button>

Related

Get values from ID HTML and save in array

I'm doing a view where once I click I'm displaying
For Loop
I am having a view that captures a QR code and displays it on the screen, what I want to do next is take these values by iterating the elements with a for loop and save it in an array, in this case my ID is id="scanned-result" and I want to iterate each containing values and saving to an array.
I am doing this but for some reason it is not performing the operation correctly. I would like to know what I should correct?
function SubmitCodes() {
var QRCodeval= document.querySelectorAll('scanned-result');
var arr = [];
for (var i in QRCodeval) {
alert(QRCodeval[i]);
arr.push( QRCodeval[i]);
}
alert(arr.val);
}
VIEW
<div class="container">
<div class="row">
<div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
<div id="reader" style="display: inline-block;"></div>
<div class="empty"></div>
<div id="scanned-result">
<div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
<div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div></div>
</div>
</div>
</div>
There are several issues with your code. To select element by ID using querySelector you need to use # selector, also to select the divs inside you can use element > element selector.
var QRCodeval = document.querySelectorAll("#scanned-result>div");
querySelectorAll returns a nodeList. So you need to iterate through it to get value of individual elements. But you should not use for..in. You can use forEach instead.
function submitCodes() {
var QRCodeval = document.querySelectorAll("#scanned-result>div");
var arr = [];
QRCodeval.forEach((el) => arr.push(el.innerHTML));
console.log(arr)
}
submitCodes();
<div class="container">
<div class="row">
<div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
<div id="reader" style="display: inline-block;"></div>
<div class="empty"></div>
<div id="scanned-result">
<div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
<div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div>
</div>
</div>
</div>
</div>
To get the text inside of the elements you can use innerHTML.
Since there is no <scanned-result></scanned-result> element on your page, as charlietfl pointed out, you won't get any results.
Since your HTML markup is the following:
<div id="scanned-result">
<!-- … -->
</div>
You are looking for an ID.
And the valid ID query in a CSS selector is a #, because of that you should query like:
var QRCodeval = document.querySelectorAll('#scanned-result')
I've changed the iteration to fill the array with the lines inside the ID scanned-result. Would that help ?
function SubmitCodes() {
var QRCodeval = document.getElementById('scanned-result').children;
var arr = [];
for (var i = 0; i < QRCodeval.length; i++) {
arr.push(QRCodeval[i].innerText)
}
console.log(arr)
}
<div class="container">
<div class="row">
<div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
<div id="reader" style="display: inline-block;"></div>
<div class="empty"></div>
<div id="scanned-result">
<div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
<div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div>
</div>
</div>
</div>
</div>

Javascript reorder HTML element based on attribute value

I have the following HTML:
<div class="wrapper">
<div class="item" id="item-1">
</div>
<div class="item" id="item-2">
</div>
<div class="item" id="item-3">
</div>
</div>
And in javascript I'm currently applying filters & sort to the results of an array:
results = Object.keys(list).filter(.....);
results = results.sort((a, b) => (....) ? 1 : -1);
// After the results have been filtered & sorted, hide all HTML elements:
document.querySelectorAll('.item').forEach(i => i.classList.add('d-none'));
// And then proceed to show only the results that have been filtered & sorted:
results.forEach(index =>
{
let id = list[index].id;
let item = document.getElementById('item-' + id);
item.classList.remove('d-none');
});
This works great. The problem is that now I need to move the HTML elements according to the results array, specifically with the id field.
A) Expected output: Array ids [2, 1]
<div class="wrapper">
<div class="item" id="item-2">
</div>
<div class="item" id="item-1">
</div>
<div class="item d-none" id="item-3">
</div>
</div>
B) Expected output: Array ids [2]
<div class="wrapper">
<div class="item" id="item-2">
</div>
<div class="item d-none" id="item-1">
</div>
<div class="item d-none" id="item-3">
</div>
</div>
You can move elements to the top, using prepend function.
On bellow example, I only implement the logic about move elements, and I didn't protected against non existent elements.
You should add your logic's about filtering, etc. and protect for possible errors.
function sortDivs() {
let list = [2, 1];
let mainDiv = document.querySelectorAll('.wrapper')[0];
list.reverse().forEach(n => mainDiv.prepend(document.getElementById('item-'+n)));
}
.item {
border: black solid;
}
<div class="wrapper">
<div class="item" id="item-1">
item-1
</div>
<div class="item" id="item-2">
item-2
</div>
<div class="item" id="item-3">
item-3
</div>
</div>
<br>
<button onClick="sortDivs()"> sort DIVs</button>
One way would be to
iterate the result ids and get the correspondig object from the dom (combined with your last .forEach round removing the d-done class)
get all d-done elements and combine both lists
convert to html and reset innerHTML of the wrapper
let results = [2,1]
let wrapper = document.getElementById('wrapper-id')
wrapper.innerHTML = results.map(id => document.querySelector('#item-' + id))
.concat([...document.querySelectorAll('.d-none')])
.map(elem => elem.outerHTML)
.join('')
<div class="wrapper" id="wrapper-id">
<div class="item" id="item-1">
item-1
</div>
<div class="item" id="item-2">
item-2
</div>
<div class="item d-none" id="item-3">
item-3
</div>
</div>
Solved.
I had several problems:
The first one was instead of using Object.keys(results).filter I should be using results.filter, because I don't need to get only the Keys, which was making things way harder.
Secondly, the logic to apply in order to have everything re-organizing according to multiple filters is:
Sort / filter everything
Hide all items (using d-none)
Grab all the wrapper children const wrapperItems = wrapper.children
Create a variable named wrapperNewItems that holds the new sorted/filtered items
Create a variable that holds which ID's (item-1, item-2, etc) have been sorted/filtered
Push the items sorted into the variable and remove d-none
Push the items that were NOT sorted into the variable and keep d-none
Translated into code:
document.querySelectorAll('.item').forEach(i => i.classList.add('d-none'));
const wrapper = document.getElementsByClassName('wrapper')[0];
// Saves the existing children
const wrapperItems = wrapper.children;
// Holds the new items ordered perfectly
let wrapperNewItems = [];
// Holds names that were filtered (item-1, item-2, etc)
let listOfNamesFiltered = [];
// Shows only the items filtered
results.forEach(item =>
{
let name = 'item-' + item.id;
let el = document.getElementById(name);
el.classList.remove('d-none');
wrapperNewItems.push(el);
listOfNamesFiltered.push(name);
});
for (let i = 0; i < wrapperItems.length; i++)
{
let item = wrapperItems[i];
let name = item.id; // id="" already contains "item-{id}"
// If the name already exists in the list, we won't add it again
if (listOfNamesFiltered.includes(name))
continue;
wrapperNewItems.push(item);
}
// Clears the div
wrapper.innerHTML = '';
// Appends the items once again
for (let i = 0; i < wrapperNewItems.length; i++)
wrapper.innerHTML += wrapperNewItems[i].outerHTML;

How to trigger a click on an element in javascript

I have the following Html:
<div class="box-row">
<div class="box c2-3">
<div class="box-overlay"></div>
<div class="box-letter"></div>
</div>
<div class="box c2-4">
<div class="box-overlay"></div>
<div class="box-letter"></div>
</div>
<div class="box c2-5">
<div class="box-overlay"></div>
<div class="box-letter"></div>
</div>
<div class="box c2-6 trr">
<div class="box-overlay trr"></div>
<div class="box-letter"></div>
</div>
</div>
I want to randomly select one of the elements with class: c2-3, c2-4, c2-5, c2-6 and trigger a click.
This is the code I have thus far:
var map = [
'c2-3', 'c2-4', 'c2-5', 'c2-6',
];
var x = Math.floor((Math.random() * 4));
var element = document.getElementsByClassName(map[x]);
At this point I want to trigger the click and am unsure how to do it:
element.trigger('click'); ??
Use element.click(); instead of element.trigger('click'); but also, you need to either get only a single element, or loop over the returned HTMLCollection from .getElementsByClassName().
For example, to loop:
var elements = document.getElementsByClassName(map[x])
elements.forEach(element => element.click())
...Or, to get a single element (still using getElementsByClassName):
var element = document.getElementsByClassName(map[x])[0]
element.click()
Alternatively, you can use querySelector:
var element = document.querySelector(`.${map[x]}`)
element.click()

how to check if a div with a certain value is duplicated and then hide the duplicated div in jQuery

I am having trouble checking if a div with a certain value is duplicated and then hiding that duplicated div.
Here's my code:
<div class="div">Java</div>
<div class="div">Python</div>
<div class="div">Php</div>
<div class="div">Java</div>
<div class="div">Java</div>
<div class="div">Java</div>
Try this,I hope this is what you are looking for.
var a = new Array();
$('.div').each(function(index) {
text = $(this).text();
if($.inArray(text, a)!=-1){
$(this).closest('.div').hide();
}else{
a.push(text);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">Java</div>
<div class="div">Python</div>
<div class="div">Php</div>
<div class="div">Java</div>
<div class="div">Java</div>
<div class="div">Java</div>
You need to loop through all div classes and then check if the current div class is already exist, this will check using div class html content. Script is like this:
var divs = [];
$(".div").each(function(i,v){
if(divs.indexOf(v.html())>=0){
divs.push(v.html()); //collect all unique divs
}else{
//this is the duplicate div. need to hide it.
$(this).hide();
}
});
well, it depends, if you want to check if hes inside text is the same then you can run over all the divs and use something like array to check if already exists.
var exists = [];
$(document).ready(function(){
$(".div").each(function(){
var text = $(this).text();
if(exists.indexOf(text) != -1){
$(this).hide();
}else{
exists.push(text);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">Java</div>
<div class="div">Python</div>
<div class="div">Php</div>
<div class="div">Java</div>
<div class="div">Java</div>
<div class="div">Java</div>
You can wrap all the elements you want to remove the duplicates in a class .container
You can then get all the children of this element, and turn it into an array using .toArray(). You can then use a Set to remove all the duplicates in this array:
and then use a Set to remove the duplicates within the array and then display this:
const unique = $('.container').children().toArray().map(e => '' + e.outerHTML);
const elems = [...new Set(unique)].join('');
$('.container').html(elems);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="div">Java</div>
<br />
<div class="div">Python</div>
<div class="div">Php</div>
<div class="div">Java</div>
<div class="div">Java</div>
<div class="div">Java</div>
</div>
If you wish you could use this as a one-liner:
$('.container').html([...new Set($('.container').children().toArray().map(e => ''+e.outerHTML))].join(''));

Copy Class Values to Div

I have HTML File:
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="Function()">Whatever</button>
<div id="result"></div>
I'd like my function to take values from all four divs with class "um-field-value"
<div class="um-field-value">Value1</div>
And past them in Div "result"
Essentially, I want a script to simply copy values given in class um-field-value and paste it in a "result" div. I tried following:
function Function() {
var x = document.getElementsByClassName("um-field-value");
document.getElementsById('result').innerHTML = x;
}
But that doesn't work at all.
I am somewhat new to coding so I am not entirely sure if it is even possible. Googled for over an hour but couldn't find any solutions.
document.getElementsByClassName gets the HTML nodes themselves but then you have to extract the values from within the HTML nodes, combine them, and set that to your result div. Example snippet below:
function myFunction() {
var valueNodes = Array.prototype.slice.call(document.getElementsByClassName("um-field-value"));
var values = valueNodes.map(valueNode => valueNode.innerHTML);
var result = values.join(' ');
document.getElementById('result').innerHTML = result;
}
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="myFunction()">Whatever</button>
<div id="result"></div>
Use querySelectorAll to get all the dom with this class um-field-value and iterate over that to get the innerHTML
There is a typo in your code.It is getElementById instead of getElementsById. There is an extra s
function Function() {
var x = document.querySelectorAll(".um-field-value");
let result = '';
for (var y = 0; y < x.length; y++) {
result += x[y].innerHTML;
}
document.getElementById('result').innerHTML = result;
}
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="Function()">Whatever</button>
<div id="result"></div>
You are on the right track. document.getElementsByClassName will return a NodeList. You need to get the innerText for each of the elements in that list. Depending on the browser you can either use forEach or a regular for loop to iterate over the list.
function Function() {
var fieldsList = document.getElementsByClassName("um-field-value");
var fieldValues = [];
fieldsList.forEach(function(field) { fieldValues.push(field.innerText) });
document.getElementsById('result').innerHTML = fieldValues.join(", ");
}
This is a simple and readable solution that uses a loop to get the text inside each element and add it to a string. getElementsByClassName returns an array of all elements found, so a loop is needed to get the text inside each with textContent.
function Function() {
var result = '';
var fields = document.getElementsByClassName("um-field-value");
for (var i=0; i<fields.length; i++) {
result += fields[i].textContent + '\n';
}
document.getElementById('result').innerHTML = result;
}
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="Function()">Whatever</button>
<div id="result"></div>

Categories

Resources