0

I've seen many threads about getting an array of option value but they're all done by id. Unfortunately, my select field does not have a proper id. How can I get an array of all values in the select tag by the name using Jquery?

  <select name="groupa">
        <option value="1">A</option>
        <option value="2">B</option>
        <option value="3">C</option>
    </select>

I'd expect a result like this:

[
   '1' => 'A'
   '2' => 'B'
   '3' => 'C'
]

p/s: I've tried some similar codes but did not work.

1

1 Answer 1

1

This should do it:

    var arr = [];

    $("select[name='groupa'] > option").each(function() {
       //doSomething
       //e.g push to arr
       arr.push(this.value);
    });
    console.log(arr);

To get all values into an array you can do:

    var arr = $("select[name='groupa'] > option").map(function(){
       return $(this).val();
    }).get();
    console.log(arr);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. But can u play with .map() function, it'd be nice.
I adapted the answer. I hope this fits your needs.
Many thanks. It turns out the issue was caused by an another factor and my syntax was right. Anyway, you answer is correct.

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.