Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you select items in a listbox using jQuery?

Tags:

jquery

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

like image 947
leora Avatar asked Apr 04 '10 12:04

leora


2 Answers

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.

like image 159
Nick Craver Avatar answered Sep 28 '22 16:09

Nick Craver


In ListBox that have multi selection mode use it :

  $('#ListBox1').find('option:selected').map(function () {
  alert($(this).text());
  });
like image 40
Ali Sarshogh Avatar answered Sep 28 '22 17:09

Ali Sarshogh