John Crain
John Crain

Reputation: 61

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!

Upvotes: 6

Views: 6597

Answers (6)

Pointy
Pointy

Reputation: 413712

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.

Upvotes: 12

Sarfraz
Sarfraz

Reputation: 382666

Try with jquery's map function:

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

// use ajax to send datearray

Upvotes: 4

Greg
Greg

Reputation: 23463

Building on the other answers, here is a simplified version:

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

The map function gets the id from each element, and the get function returns an array. Within the anonymous function passed to map, this refers to to each selected element in turn.

Upvotes: 1

Josh Stodola
Josh Stodola

Reputation: 82483

The array should be loaded; you can send it to the server using jQuery.post...

$.post("process.php", datearray, function(dat) {
  alert('Response: ' + dat);
});

Upvotes: 0

Koen
Koen

Reputation: 3686

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

Upvotes: 1

3urdoch
3urdoch

Reputation: 7322

IT all looks good to me, the array will be populated and be available where you have placed the comment. Have faith in yourself.

Upvotes: 0

Related Questions