Implement an array using foreach in Javascript - javascript

I've a several li elements which have as class : multiselect_selected_profil.
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="60">
<span class="multiselect_profil">C1</span>
</li>
I would like that for each li that has this specific class, I get its data-id and then put it into an array. At then end of the process I would like to have an array which contains all the ids.
Here is what I've tried :
$(".multiselect_selected_profil").each(function(){
var iObjetId = $(this).attr('data-id');
// ???
}

var ids = []
$(".multiselect_selected_profil").each(function(){
var iObjetId = $(this).attr('data-id');
ids.push(iObjetId);
}
Create an empty array and push ids

You can use map() to create an array from a set of matched elements:
var arr = $(".multiselect_selected_profil").map(function() {
return $(this).data('id');
}).get()

Have a look attached snippet.
var dataid = []; //Initialize the array variable
$(".multiselect_selected_profil").each(function(){
var iObjetId = $(this).attr('data-id');
dataid.push(iObjetId);
});
alert(dataid);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="60"><span class="multiselect_profil">C1</span></li>
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="61"><span class="multiselect_profil">C2</span></li>
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="62"><span class="multiselect_profil">C3</span></li>
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="63"><span class="multiselect_profil">C4</span></li>
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="64"><span class="multiselect_profil">C5</span></li>

var ids = [];
$(".multiselect_selected_profil").each(function(){
if($(this)..hasClass( "specific_class_name" )){
ids.push($(this).attr('data-id'));
}
});
now you will get all ids those contains specific class

The fastest way would be specifying the data-id right in the selector description and use toArray() function to retrieve all the elements contained in the jQuery set, as an array:
var arr = $(".multiselect_selected_profil[data-id]").toArray();

Related

How to get jquery array from html each list item

<ul>
<li>listitem1</li>
<li>listitem2</li>
<li>listitem13</li>
</ul>
I have something like this on HTML file. So how can I get that each list item in my jQuery file as array
like this
var asmg = ["listitem1","listitem2","listitem3"];
use the jQuery.map() and .get() to process a plain array.
var asmg = $( "li" )
.map(function() {
return $(this).text();
}).get();
console.log(asmg);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>listitem1</li>
<li>listitem2</li>
<li>listitem13</li>
</ul>
try with foreach loop :
function getArray(ul){
asmg = [];
ul.find('li').each(function(){
asmg.push($(this).text());
});
return asmg;
}
console.log(getArray($('ul')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>listitem1</li>
<li>listitem2</li>
<li>listitem13</li>
</ul>
Try following
$(function(){
var asmg = [];
$("ul > li").each(function(i, li){
asmg.push($(li).text());
});
console.log(asmg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>listitem1</li>
<li>listitem2</li>
<li>listitem13</li>
</ul>
You can use vanilla JavaScript to achieve this:
Select all the li elements
document.querySelectorAll('li')
unpack them in an array
[...document.querySelectorAll('li')]
map this array to get the text content of each li item.
[...document.querySelectorAll('li')].map(e => e.textContent)
Here is the code:
const li = [...document.querySelectorAll('li')].map(e => e.textContent)
console.log(li)
<ul>
<li>listitem1</li>
<li>listitem2</li>
<li>listitem13</li>
</ul>
var asmg = Array.from(document.querySelectorAll('li')).map(e => e.textContent);
var asmg = Array.from(document.querySelectorAll('li')).map(e => e.textContent);
console.log(asmg);
<ul>
<li>listitem1</li>
<li>listitem2</li>
<li>listitem3</li>
</ul>
var varObject = $('ul li').map(function(){
return $(this).text();
}).get();
//converting to array
var aiMsg = $.makeArray(varObject);
this code works for me.
thanks for all the answer

jquery append where trigger is bigger then

I'm trying to append child to listing but what I want to do is to append it in the place ordering by data-price.
my template:
<ul>
<li data-price="18"></li>
<li data-price="27"></li>
<li data-price="28"></li>
<li data-price="31"></li>
<li data-price="99"></li>
<li data-price="101"></li>
<li data-price="191"></li>
</ul>
my js what I've tried so far:
var template = '<li data-price="100"></li>';
$('ul').find('li').filter(function() {
return $(this).attr("data-price") > 99;
}).after(template);
so if the price is 100 it should be appended by price ordering and in this case where price is greater then 99 but less then 101, but i dont have any working solution for that.
I'm not sure if this is the best way to do it and if it'll always work, but it works for your question. Try it out
var template = '<li data-price="100">100</li>';
var checkPrice = $(template).attr("data-price");
var appendBefore = $('ul li').filter(function(){
return parseInt($(this).attr("data-price")) > checkPrice-1;
})[0];
console.log(appendBefore);
$(appendBefore).before(template);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-price="18">18</li>
<li data-price="27">27</li>
<li data-price="28">28</li>
<li data-price="31">31</li>
<li data-price="99">99</li>
<li data-price="101">101</li>
<li data-price="191">191</li>
</ul>
check if that is what you need:
https://jsfiddle.net/3er0da9c/
var template = '<li data-price="100"></li>';
var itemValue = parseInt($(template).attr('data-price')); //Getting value that we should compare
var value, smaller = 0, smallerItem; //We will need those variables to know where to place our "template"
smallerItem = $('ul > li:first-of-type'); //Set the smaller item in our list to be the first one. Change that if your list wont be always asc sorted
$('ul > li').each(function(){ //run through the given list
value = parseInt($(this).attr('data-price'));
if ((itemValue == value) || ( itemValue > value )){ //if the actual item is equal, put our item right after it. If the item is smaller then our number, we save it and keep running
smaller = value;
smallerItem = $(this);
}
});
if (smaller != 0) //This will happens when we have at least one item smaller then our number
smallerItem.after(template);
else
smallerItem.before(template); //else, we add our number at top

Adding extra values to JS Object

Ok I have an HTML list containing the data I need.
It looks like this
ul
li[data-trainer]>trainee
li[data-trainer]>trainee
li[data-trainer]>trainee
I iterate it and want to make an object that looks like this
{
"Trainer":{0:Trainee1},
"Trainer2":{1:Trainee2,2:Trainee3,3:Trainee4}
}
I tried this and a bunch more
var Data = new Object();
var i = 0;
$(".blah-blah-ul li.active").each(function(){
i++;
var trainer = $(this).attr("data-trainer");
var trainee = $(this).text();
Data[trainer] = {};
Data[trainer][i] = trainee;
})
console.log(Data);
Data[trainer][i] = trainee leaves me with only the last trainee in the list.
Data from console.log:
Object
Trainer1: Object
2: Trainee2
Trainer3: Object
4: Trainee6
I tried making an array and using push or making a string but that didn't work.
If someone could please recommend a proper solution, it would be greatly appreciated.
Here's the HTML
<ul class="blah-blah-ul">
<li class="active" data-trainer="Trainer1">Trainee1</li>
<li class="active" data-trainer="Trainer1">Trainee2</li>
<li data-trainer="Trainer2">Trainee3</li>
<li data-trainer="Trainer2">Trainee4</li>
<li class="active" data-trainer="Trainer3">Trainee5</li>
<li class="active" data-trainer="Trainer3">Trainee6</li>
</ul>
Your problem was in order to have more than one value assigned to the element in the array, the sub element must be an array. This allows for adding multiple Trainee to the Trainer item in the Data object.
var Data = new Object();
var i = 0;
$(".blah-blah-ul li.active").each(function(){
i++;
var trainer = $(this).attr("data-trainer");
var trainee = $(this).text();
if(typeof Data[trainer] === 'undefined') {
Data[trainer] = {};
}
Data[trainer][i] = {trainee};
})
console.log(Data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="blah-blah-ul">
<li class="active" data-trainer="Trainer1">Trainee1</li>
<li class="active" data-trainer="Trainer1">Trainee2</li>
<li data-trainer="Trainer2">Trainee3</li>
<li data-trainer="Trainer2">Trainee4</li>
<li class="active" data-trainer="Trainer3">Trainee5</li>
<li class="active" data-trainer="Trainer3">Trainee6</li>
</ul>
Documentation on Javascript Arrays using Push, can be found here w3schools
var Data = {};
var i = 0;
$(".blah-blah-ul li.active").each(function(){
i++;
var trainer = $(this).attr("data-trainer");
var trainee = $(this).text();
Data[trainer] = {};
Data[trainer][i] = trainee;
})
console.log(Data);
Try the following approach:
Data[trainer][i] = trainee;
and you can find more info here:
How can I add a key/value pair to a JavaScript object?

jQuery find data attributes with one datakey and multiple values

I want to retrive all the objects with one datakey and multiple values, for QuickSand:
<ul>
<li data-company="Microsoft">Steve</li>
<li data-company="Google">Jobs</li>
<li data-company ="Facebook">Michael</li>
<li data-company ="Google">Richard</li>
<li data-company ="Facebook">Tim</li>
</ul>
How can i retreve all the li items with data-company Microsoft and Google (these two values are in a array) like this:
var itemes = $('ul').find('li[data-comapany={"Microsoft","Google"}]');
Thank you.
you could create an array of the required companies, and check for each li if the data is contained in that array:
var companies = ["Microsoft", "Google"];
$(function() {
var items = $('ul li').filter(function() {
return $.inArray($(this).data("company"), companies) > -1;
});
items.css({
"position": "relative",
"margin-left": "25px"
});
console.log(items);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-company="Microsoft">Steve</li>
<li data-company="Google">Jobs</li>
<li data-company="Facebook">Michael</li>
<li data-company="Google">Richard</li>
<li data-company="Facebook">Tim</li>
</ul>
You could filter it:
var itemes = $('ul').find('li').filter(function(){
return $(this).data('company').match(/Microsoft|Google/);
});
-DEMO-
To handle case for LI without any data-company set, you should use:
var itemes = $('ul').find('li').filter(function(){
var data = $(this).data('company');
return data ? data.match(/Microsoft|Google/) : null;
});
You can also combine selectors:
var items = $("[data-company*='Microsoft'], [data-company*='Google']");
jsFiddle
You could do it like this:
var companies = ['Google', 'Microsoft', 'Waffle House'];
companies.forEach(function(company, index) {
companies[index] = "li[data-company='" + company + "']";
});
$('ul').find(companies.join(',')).css('background', 'red');

Select sub element based on classes it has

Below is the HTML that I have
<ul id="QBS">
<li>
<a class="qb_mode starting Rodgers" href="#">See Stats</a>
</li>
<li>
<a class="qb_mode Manning" href="#">See Stats</a>
</li>
<li>
<a class="qb_mode Brady" href="#">See Stats</a>
</li>
</ul>
I want to find this unordered list, then tell which item has the starting qb class and then return the class that has their name (brady rodger manning) etc.
What's throwing me in a loop is the fact that the link is wrapped in the list element.
Here is what I am trying:
element = $("#qbs"); // pretty sure I want this vs getElementbyDocumentID
children = element.children();` // gets me all the list elements
for (i=0;i<children.length;i++) {
grandchild = children[i].children();
???? How would I get the 3rd class on this element?
}
Sorry about the formatting.
How about this?
var allClasses = $("#QBS").find('li a[class^="qb_"]')
.map(function () {
return this.className.split(" ").pop();
}).get();
console.log(allClasses);
Fiddle
Provided the class started with qb_* is at the beginning and you want to take only the last class of the match.
if all your class names are qb_mode then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
return this.className.split(" ").pop();
}).get();
if you want all of them then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
var cls = this.className.replace(/qb_mode/,'');
return cls.trim().split(/\W+/);
}).get();
console.log(allClasses);
Fiddle
If I understood you correctly, how about:
var name = $('#QBS a.qb_mode.starting').prop('class').replace(/\s*(qb_mode|starting)\s*/g,'');
console.log(name); // Rogers
See demo here.
a=document.getElementById('QBS');
var b=a.getElementsByClassName("qb_mode");
var i, j=b.length, result=[];
for(i=0;i<j;i++) {
c=b[i].className.split(" ");
result.push(c.pop());
}
return result;
fiddle http://jsfiddle.net/3Amt3/
var names=[];
$("#QBS > li a").each(function(i){
var a=$(this).attr("class").split(" ");
names[i]=a[(a.length-1)];
console.log("Name is " + names[i]);
});
or a more precise selector
$("#QBS > li a.qb_mode").each( ....

Categories

Resources