Store an array of select in a js variable

Asked

Viewed 613 times

1

I need to go through several select and store your value in an array with jQuery, but I can’t. How can I do this?

2 answers

0

I’m not sure what you want, but see if you can help:

var array = new Array();
$('select').each(function(index, el) {
  array.push($(el).val());
});
console.log(array);

If you want to take only the selected options:

var array = new Array();
$('select option:selected').each(function(index, el) {
  array.push($(el).val());
});
console.log(array);

0


You can create a collection with $('select') and then use .map() to generate an array, and .get() to convert from a jQuery collection to a native array.

An example would be like this:

var values = $('select').get().map(function(select){
    return select.value;
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.