Javascript/jQuery Dynamic Array - javascript

I am trying to create a dynamic array using JS/jQuery. The HTML structure is:
<ul>
<li><img src="1"/></li>
<li><img src="2"/></li>
<li><img src="3"/></li>
</ul>
I am trying to create a new array of the image sources, so it ends up looking like:
var imagesArray = [1, 2, 3];
I thought I could use the jQuery .each() method...but I keep getting lost. If you can please provide an explanation I would really appreciate it.
thanks!

var imagesArray = $('img').map(function(){ return this.src; }).get();
Here's a demo: http://jsfiddle.net/pkeBZ/
jQuery's .map() method loops through all the elements, collects whatever is returned from your callback function, and creates a new array out of it.
However, the returned result behaves like an array, but is really an jQuery object (granted, it probably makes no difference in your use case).
If you want to convert a jQuery object into an array, you can use jQuery's .get() method.

You thought correct :) You can use the jQuery .each() method.. as below..
<script type="text/javascript">
$(document).ready(function(){
var imagesArray =new Array();
$("ul li img").each(function(){
imagesArray.push($(this).attr('src'));
});
console.log(imagesArray); // this returns ["1", "2", "3"]
});
</script>

Use this code snippet to loop an array in jquery
1) First we declare an arrray
var MapAreas = [];
2) Now we loop using foreach
$.each(MapAreas, function (index, value) {
alert(index + ':' + value);
}
3) To check if a value is already present in an array use this code snippet
if ($.inArray(value, MapAreas) >= 0) {}
4) To remove an item from the array use this function
RemoveItemFromArray(value, arr) {
return jQuery.grep(arr, function (elem, index) {
return elem !== value;
});
}

Related

Pass string to jQuery selector

I have several classes with the names like so:
.x-string
.y-string
.z-string
A dynamic part and a constant one. I have made an array containing the dynamic parts (x, y, z).
I want to loop through the array, take each name, concatenate "-string" to the end of it, and pass it as a class to be selected in jQuery.
Sort of like:
$(classList).each(function () {
let newClass = '.' + this + '-string'
$('.this-string')...
}
Is this possible and how would I go about it? Cheers.
I want to loop through the array,
jQuery works with arrays differently than it works with it's on jQuery object wrapper. So to loop through an array you'd use jQuery.each() or $.each().
var myArray = ['x', 'y', 'z'];
$.each(myArray, function(idxArray, valArray) {
// code
});
concatenate "-string" to the end of it, and pass it as a class to be selected in jQuery
Now we can use the jQuery selector with .each() to find matching elements
var myArray = ['x', 'y', 'z'];
$.each(myArray, function(idxArray, valArray) {
var selector = "." + valArray = "-string";
$(selector).each(function(idxElement, valElement) {
var $this = $(valElement);
// or
var $this = $(this);
$this.fadeOut();
});
});
It's important to note that the second .each() should only be used if you have specific logic to run after an item is found. If the code is the same for every element, then each is not needed:
var selector = "." + valArray = "-string";
// fadeOut all matching elements
$(selector).fadeOut();
It's also important to note that if the logic is as simple as your example, you should not need to loop at all. You can create a comma delimited string containing all the selectors.
var myArray = ["a","b","c","d"];
var selector = myArray
.map(s => "." + s + "-string")
.join();
$(selector).css("color", "red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Black</div>
<div class="a-string">Red</div>
<div>Black</div>
<div class="b-string">Red</div>
<div>Black</div>
<div class="c-string">Red</div>
<div>Black</div>
<div class="d-string">Red</div>
JQuery
$.each is used for iteration of the array. Which takes two arguments [index, element].
The element is the element of an array. Don't use this because it's not recommended!
$(classList).each((idx, elem) => {
$('.'+elem+'-string')
});
Native
To use the native method we'll use the [].forEach or for...of iteration.
NOTE: for...of method has only support from ES6.
// for...of loop
for(i of elem)
$(`.${elem}-string`)
// forEach loop
elem.forEach(function(elem) {
$('.'+elem+'-string')
});
Some general issues with your usage of .each. Try:
$(classList).each(function(idx, cls) {
let newClass = '.' + cls + '-string';
$(newClass) ...
});

How to iterate in Jquery over json string with multiple objects

I'm wondering how I can access each object in this json string via jquery.
The string returned looks like:
{"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]}
I need access to both the Appointments object as well as the Sessions object, I can't seem to figure it out.
I tried to access the Appointments object by index like:
$.each(data, function (index, element) {
$.each(data, function (index, element) {
//alert(JSON.stringify(element, null, 4));
alert(element.Appointments[index]);
});
//value = new Date(parseInt(element.Appointments.substr(6)));
//var rowContent = "<tr><td>" + value + "</td></tr>";
//$('#appointmentsTable tbody').append(rowContent);
});
This does not work however, thoughts?
You don't have to access element by element.Appointments[index] when you are looping though an array by $.each.
For example
var data = {"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]};
To loop though object in data.Appointments, you simply do this
$.each(data.Appointments, function(index, element){
console.log(element);
});
To loop though object in data.Sessions, you simply do this
$.each(data.Sessions, function(index, element){
console.log(element);
});
For more example about $.each, please refer to JQuery API Documentation here.
You don't actually need jquery for this at all.
You could use plain javascript. If your project uses ES6, you could write it as:
// extract appointments and sessions from data
let { Appointments, Sessions } = data
// iterate over appointments
Appointments.forEach((appointment, index) => { console.log(appointment) })
// iterate over sessions
Sessions.forEach((session, index) => { console.log(session) })
Basically you don't really need index inside your iteration callback - you can directly access the elements you are iterating over instead. The same would apply to your jquery function as well.
If you prefer to use jQuery, your code could be rewritten as:
$.each(data.Appointments, (index, elem) => alert(elem))

Impossible to bind an event to an array containing jquery objects

I create dynamically a list content:
for (var i = 0; i<length; i++) {
var $li = $('<li />', {
text: ....
}).appendTo($list);
myArray.push($li);
// This doesn't work
$(myArray).click(function (e) { alert('cc'); });
But when I get the parent of the created elements it works
// This works
$('ul.liste').first().find('li').click(function (e) {alert('cc'); });
What's the difference between between $(myArray) and $('ul.liste').first().find('li')?
How to correctly convert a js array to a jquery collection? I thought wrapping the array with $() would work but obviously not.
Instead of pushing, you can use add:
var $set = $();
for (var i = 0; i<length; i++) {
var $li = $('<li />', {
text: ....
}).appendTo($list);
$set = $set.add($li);
}
$set.click(...
If you prefer to build a native array and then convert it to a jQuery collection, then you can do
var $set = $.add.apply($(), myArray);
myArray is native array, You need jQuery object to bind event handler which $('ul.liste').first().find('li') returns thus it works.
You can use .add() to create collection of jQuery object then use it to bind event handler.
//Create empty jQuery object
var myArray = $([]);
var $list = $('.list')
for (var i = 0; i < 5; i++) {
var $li = $('<li />', {
text: i
}).appendTo($list);
myArray = myArray.add($li);
}
// This doesn't work
myArray.click(function(e) {
console.log(this.textContent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='list'>
</ul>
You need to loop over the array instead,
Following is incorrect as it is not binding a click event on corresponding element.
$(myArray).click(function (e) { alert('cc'); });
Instead loop as,
$(myArray).each(function(){
$(this).click(function (e) { alert('cc'); });
});
1) What's the difference between between $(myArray) and $('ul.liste').first().find('li')?
Here, myArray is not any jQuery object but a normal array containing jQuery objects as its element. You never bind event to array or string or any other datatype. you always bind event to jQuery object (that contains some DOM elements). Therefore, instead of binding myArray, you should bind every element of myArray one by one.
When you use $('ul.liste'), it works fine because it is a jQuery object with some DOM element in it.
2) How to correctly convert a js array to a jquery collection? I thought wrapping the array with $() would work but obviously not.
You don't convert js Array to jQuery object. But you convert any DOM element to jQuery object as:
For eg,
var elem = document.getElementById("myElem"); // a DOM element
$(elem) //a jQuery object
Arrays are there just to save some data not for DOM manipulations.

$.grep filter with contains

I am trying to filter an array with grep to apply CSS. My code is like below.
var depos = $('.panel-default > .panel-heading');
var chkd = ['ABC','XYZ'];
var found_p = $.grep(depos, function(v) {
return jQuery.inArray(v.innerText,chkd);
});
The first issue is that found_p is not filtering the needed array values from chkd. After filtering it, how can I apply CSS? I tried like below but it fails
$(found_p[0]).css('background-color', 'red');
Can anybody help me out with this.
Assuming from your code that you're trying to find the elements that have innerText matching a value in the chkd array, you can use the filter() method. Try this:
var $depos = $('.panel-default > .panel-heading');
var chkd = ['ABC','XYZ'];
var $found_p = $depos.filter(function() {
return $.inArray($(this).text(), chkd) != -1;
});
The $found_p variable will then hold a jQuery object with all matched elements. You can apply CSS to them like this:
$found_p.css('background-color', 'red');
Example fiddle
However, I would suggest using CSS classes instead of adding inline styles as it is much better practice.

How can I get values from a list (not having items ids) with jQuery?

So I have a list with lots of items like below:
<ul id="usersList">
<li><FORM><INPUT class="eButton" type="button" value="robot669394444" onClick="openWin('robot669394444',1280,720)"></FORM></li>
<li><FORM><INPUT class="eButton" type="button" value="robot6693925" onClick="openWin('robot6693925',1280,720)"></FORM></li>
</ul>
I want to get all INPUT values using jQuery into an array. How to do such thing?
var vals = $("form input").map(function() {
return $(this).val();
});
Alternatively (more cleanly)
var vals = [];
$("form input").each(function() {
vals.push( $(this).val() );
});
The second alternative is more clean since it leaves you with a plain vanilla array. The result of map() still is a jQuery object. Since these are (and behave exactly like) arrays, this might not be a problem. But it's useful to keep that subtle difference in mind.
It's not always possible to store all params (keys and values) in an object, because two inputs can have same name.
But you can use: $('form.myform').serializeArray() to get an object like [{param1:value2}, {param2: value2}]
Or use
$('form.myform').serializeArray().map(function(e){ return e.value;})
to get list of all values [value1, value2, ...]
I am not sure of a way to do it with Jquery, but using simple javascript can help
var uL=document.getElementById("usersList");
var i=0;
var inArr=new Array();
while(uL.getElementsByTagName("FORM")[i]){
inArr.push(uL.getElementsByTagName("FORM")[i].getElementsByTagName('input')[0]);
alert(inArr[i].value);
i++;
}
inArr will contain all the input element objects in it...

Categories

Resources