Mohamed Faisal Abbas Mohamed Faisal Abbas - 1 year ago 89
ASP.NET (C#) Question

How to get all the values of dropdownlist in var using jquery?

I want to compare string with all the values from dropdownlist. And which value of dropdownlist is matched with that string and that should be selected.


<div class="col-lg-3">
<asp:DropDownList ID="DropDownListVendor" class="form-control text-box-border" runat="server" DataSourceID="SqlDataSource1" DataTextField="vendor_name" DataValueField="vendor_name"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Nibrass_DBConnectionString %>" SelectCommand="SELECT [vendor_name] FROM [Vendor_tb]"></asp:SqlDataSource>

DropDownListVendor have return and show two values in drop down list [Compaq,Hp].

now i want to compare one string with that dropdownlistvendor value of all.
I tried this code for getting all the values of dropdownlist. But it doesn't work.

var vendorArr = [];
$('#DropDownListVendor').each(function() {
alert("vendor Array ==" + vendorArr[0]);

it returns in alert
vendor Array == Undefined

Answer Source

You can loop through options inside the select list using .map() like

var vendorArr = $("#DropDownListVendor option").map(function() {
  return this.value;

Since, asp dropdownlist id might change when rendered in html in case you are using asp master page you can use Attribute Ends With Selector to resolve that like:

var vendorArr = $("[id$='DropDownListVendor'] option").map(function() {
  return this.value;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download