1

In jQuery if you have select multiple with two values if I use:

$('select').val()

I've got:

["foo", "bar"]

but in javascript/native DOM:

$('select')[0].value

I've got:

"foo"

why I've got just the first value and not an array? How to get the same value as in jQuery? I don't see anything special in jQuery source code that check if select have attribute multiple.

Here is demo:

console.log($('select').val());
console.log($('select')[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple>
  <option value="foo" selected>foo</option>
  <option value="bar" selected>bar</option>
</select>
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • If you're looking for a way to get all values without using jQuery you can check all options for the "selected" attribute. (http://stackoverflow.com/questions/5866169/how-to-get-all-selected-values-of-a-multiple-select-box-using-javascript) – TheJP Apr 10 '17 at 08:58
  • ... Why? If you're still using jQuery to get the `select`, why do you want to use `'value'? – Cerbrus Apr 10 '17 at 08:58
  • jQuery `val` function is "special", because it loops though array – Mantas Čekanauskas Apr 10 '17 at 09:00

0 Answers0