5

The syntax to set a dropdownlist to multiple values is as following:

$("#multiple").val(["Multiple2", "Multiple3"]); 

My problem is that I don't know how many values I have. So how do I set a dropdownlist dynamicaly to multiple values with values from an array?

Luke
  • 5,771
  • 12
  • 55
  • 77

3 Answers3

3

Your code should work as seen in this live demo.

Markup:

<select multiple="multiple" id="multiple">
    <option value="1">item 1</option>
    <option value="2">item 2</option>
</select>

Script:

$('#multiple').val(['1', '2']);

Result:

enter image description here

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • It looked more like a comment to me, so I flagged it as not an answer. Without seeing it is a fiddle. I feel so dumb.... Sorry, hope you dont mind – Starx Mar 06 '12 at 12:30
  • @Starx, hopefully the administrators will read the answer more carefully before removing it. – Darin Dimitrov Mar 06 '12 at 12:36
0

do a check to know if the array has more values:

      if (array[i]) { //DO WHAT YOU NEED}
Th0rndike
  • 3,406
  • 3
  • 22
  • 42
0

It's not clear to me what you're trying to achieve. You can use an array as argument of val() and this is the result:

> Passing an array of element values allows matching <input
> type="checkbox">, <input type="radio"> and <option>s inside of n
> <select multiple="multiple"> to be selected. In the case of <input
> type="radio">s that are part of a radio group and <select
> multiple="multiple"> the other elements will be deselected.

That means that will affect in your case only a select with muptiple choice enabled (and not a simple dropdown list).

If, on the contrary by 'set to multiple values' means adding options to an existing select, val() is not built to do that (for this you can have a look here)

Community
  • 1
  • 1
mamoo
  • 8,156
  • 2
  • 28
  • 38