Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .each() with Array

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!

like image 231
John Crain Avatar asked Jun 09 '10 17:06

John Crain


People also ask

How each loop works in jQuery?

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.

How can you use array with jQuery?

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 .

How do you iterate through an element in jQuery?

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.

Can we use for loop in jQuery?

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.


3 Answers

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.

like image 78
Pointy Avatar answered Sep 28 '22 08:09

Pointy


Try with jquery's map function:

datearray = $('.selected').map(function(){
    return $(this).attr('id');
}).get();

// use ajax to send datearray
like image 43
Sarfraz Avatar answered Sep 28 '22 07:09

Sarfraz


You don't have to pass on the array to the anonymous function because it lives in the same scope.

like image 22
Koen Avatar answered Sep 28 '22 07:09

Koen