Houman
Houman

Reputation: 66320

Select a Multi-select DropDown by values with jquery

I have asked a similar question this morning, how to select a dropdown by its value rather than sequence.

The problem is now how to use a multi-select dropdown and select the options by their value rather than sequence. (e.g. I would like to select a1 and a3, by their respective primary key, 1 and 4)

<select id="id_deals-sales_item" multiple="multiple">
  <option value="1">a1</option>
  <option value="2">a2</option>
  <option value="4">a3</option>
</select>

The old way by sequence:

for (i=0; i<data[0].fields['sales_item'].length;i++)
    $('#id_deals-sales_item>option:eq(' + (data[0].fields['sales_item'][i]) + ')').prop('selected', true);

I was hoping to apply the same solution here with val(), But it doesn't work.

for (i=0; i<=data[0].fields['sales_item'].length;i++)
    $('#id_deals-sales_item').val(data[0].fields['sales_item'][i]); 

Do I have to apply a different trick here? Thanks

Upvotes: 3

Views: 287

Answers (2)

Ram
Ram

Reputation: 144659

That's because you are overriding previous selected values in each iteration, you should pass an array to the val method, try this:

var vals = [];
for (i=0; i<=data[0].fields['sales_item'].length;i++) {
    vals.push(data[0].fields['sales_item'][i]); 
}

$("#id_deals-sales_item").val(vals);

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

Try this

for (i=0; i<=data[0].fields['sales_item'].length;i++)
    $("#id_deals-sales_item option[value='" +data[0].fields['sales_item'][i] + "']").prop('selected', true);​

Upvotes: 1

Related Questions