Basically, I am trying to gather the IDs of every element with a specific class and place those IDs into an array. I'm using jQuery 1.4.1 and have tried using .each(), but don't really understand it or how to pass the array out of the function.
$('a#submitarray').click(function(){
var datearray = new Array();
$('.selected').each(function(){
datearray.push($(this).attr('id'));
});
// AJAX code to send datearray to process.php file
});
I'm sure I'm way off, as I'm pretty new at this, so any advice help would be awesome. Thanks!
each() jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.
Syntax And Declaration: var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array. Iteration Approach using JQuery: jQuery provides a generic .
The . each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.
You can use a JavaScript for loop to iterate through arrays, and a JavaScript for in loop to iterate through objects. If you are using jQuery you can use either the $. each() method or a for loop to iterate through an array.
You can use map()
too:
$('a#submitarray').click(function(){
var datearray = $('selected').map(function(_, elem) {
return elem.id;
}).get(); // edited to add ".get()" at the end; thanks @patrick
// ajax
});
The map()
method passes each index (which my example doesn't use) and element into the given function, and builds an array for you from the return values.
Try with jquery's map
function:
datearray = $('.selected').map(function(){
return $(this).attr('id');
}).get();
// use ajax to send datearray
You don't have to pass on the array to the anonymous function because it lives in the same scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With