5

I have multiple Select dropdown elements with a single class .select

<select class='select' name='select1' id='select1'>
  <option value='1'>1</option>
  <option value='2'>2</option>
  <option value='3'>3</option>
</select>

<select class='select' name='select2' id='select2'>
  <option value='4'>4</option>
  <option value='5'>5</option>
  <option value='6'>6</option>
</select>

<select class='select' name='select3' id='select3'>
  <option value='7'>7</option>
  <option value='8'>8</option>
  <option value='9'>9</option>
</select>

I know it can be achieved with the help of loop like this

var arr = [];
$('.select').each(function () {
   arr.push($(this).val());
});

But I already have so many loops in the code and I'm wondering if is there any way it can be achievable without a loop

Fiddle: http://jsfiddle.net/89cJC/

1
  • Any implementation will have loop for this :) You cant avoid Commented Mar 19, 2014 at 13:48

2 Answers 2

14

No, there's no other way to get the value from multiple elements, you have to iterate over the elements to get the value from each of them.

There are other ways to write basically the same code

var arr = $.map($('.select'), function (el) { return el.value; });

or without jQuery

var elems = document.querySelectorAll('.select'),
    arr   = [];

for (var i=elems.length; i--;) arr.push(elems[i].value);

but they all iterate, there's no other way to do that.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use jquery $.map function of jquery to deal with elements array

for example

var arr = [];
arr = $.map($(".select"),function(select){
        return $(select).val();
});

console.log(arr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.