tags:

views:

44

answers:

1

how do you programatically select items in a multiselect listbox using jquery?

+2  A: 

You can do it like this:

var valToSelect = "1";
$("#mySelect option[value='" + valToSelect + "']").attr("selected", true");

Here's a quick example: http://jsfiddle.net/ZyAHr/

Just for kicks, here's an alternative example if it fits the situation:

var values = $("select").val();
values.push("1");
$("select").val(values);

​Here's a quick example of this: http://jsfiddle.net/FBRFY/

This second approach takes advantage of the fact that .val() on a multiple <select> element returns an array, not a string. You can get it, add or remove any values, then set it again using .val() and it'll be updated with the new selection.

Nick Craver
@Nick Craver - what if i only have the value (not the display). lets say bob is the display and value is 1
ooo
@oo - This works in that case, one moment I'll update with an example.
Nick Craver