kamal
kamal

Reputation: 237

Multiple Select Options

I am trying to select items in the following select multiple by there value. The code is below:

<select id="genre" name="genre" multiple="multiple" size="9">
    <option value="1">Action</option>
    <option value="2">Adult</option>
    <option value="3">Adventure</option>
    <option value="4">Comedy</option>
    <option value="5">Drama</option>
</select>

I can select one or two options but the thing is that the number of selected options comes from user which i'm change it to something like this: 1,2,4 (by value).

Upvotes: 1

Views: 179

Answers (2)

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91299

You can select multiple options by passing an array of values to the .val() function:

$("#genre").val([1,2,4]);

If instead of an array, you have a comma delimited string, just transform it to an array using split(), before passing it to .val():

$("#genre").val("1,2,4".split(","));

From the docs:

.val( value )

value - A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.

Upvotes: 1

Rob Allen
Rob Allen

Reputation: 2911

it is difficult to determine what you are looking for, but since you want to select multiple items and you tagged it as jquery...

$('#genre').val([1,2,4]).each(function () {
    $(this).attr('selected', 'selected');

});​

Upvotes: 2

Related Questions