0
var selectedCity = [{ cityid:"1" }, { cityid:"3" }]

HTML:

City:<select name="city" multiple>
    <option value="1">Bombay</option>
    <option value="2">Chennai</option>
    <option value="3">Bangalore</option>
    <option value="4">Calcutta</option>
    <option value="5">Delhi</option>
     </select>  

I have an array object ie selectedCity with the selected city values .

Now how to set these array values as selected in the dropdown list using jquery each function such that it has Bombay(1) and Bangalore(3) as selected in dropdown list box

Mephiztopheles
  • 2,228
  • 1
  • 12
  • 25

3 Answers3

1

Here is how you should do it

 <select name="cars" multiple>
  <option selected="selected" value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option selected="selected" value="opel">Opel</option>
  <option value="audi">Audi</option>
</select`>`
0

Here you go:

var values = [];
$.each(selectedCity, function( ){
    values.push(this.cityid);
});
$('select').val(values);

Create a list, push each val to the list and set it as val from the select.
Multiselect val takes as a list: .val([1,3])

Mephiztopheles
  • 2,228
  • 1
  • 12
  • 25
0

Here is how I do it just send those names

Javascript:

//loops through objects

for (var key in selectedCity) {
     $('select>option:eq(key.cityid)').prop('selected', true);

}

HTML:

<select multiple>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>