leora
leora

Reputation: 196449

How do you select items in a listbox using jQuery?

How do you programmatically select items in a multi-select listbox using jQuery?

Upvotes: 15

Views: 31970

Answers (3)

user20178351
user20178351

Reputation:

var hasListItems = $('#ddlListItems option:selected').toArray().map(item => item.text).join();

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630349

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.

Upvotes: 27

Harry Sarshogh
Harry Sarshogh

Reputation: 2197

In ListBox that have multi selection mode use it :

  $('#ListBox1').find('option:selected').map(function () {
  alert($(this).text());
  });

Upvotes: 2

Related Questions