Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read multiple jQuery.val() into array

I have some code that looks like this that works just fine:

var info = [];
for (i = 0; i < 10; i++)
{
     info[i] = $('#info_' + i).val();
}

The problem is that this pattern is very common in my application with some minor variations. What i would like to do is to make this into a oneliner something like this where info becomes an array:

var info = $('[id^="info_"]').each().val();
like image 844
Andreas Avatar asked Jun 23 '11 10:06

Andreas


3 Answers

Found a solution thanks to Dogbert. All that was missing in his example was the .get()

Here is the solution i ended up using:

var info = $('[id^="info_"]').map(function () { return $(this).val(); }).get();
like image 190
Andreas Avatar answered Oct 23 '22 11:10

Andreas


You can use jQuery.map

var info = $('[id^="info_"]').map(function() { return $(this).val(); } )
like image 23
Dogbert Avatar answered Oct 23 '22 12:10

Dogbert


$('[id^="info_"]').each(function(){ info.push($(this).val()); });

should do

like image 2
Andy Avatar answered Oct 23 '22 12:10

Andy