Mohamed Faisal Abbas Mohamed Faisal Abbas - 3 months ago 17
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.

example

<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>
</div>


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() {
vendorArr.push($(this).attr('value'));
});
alert("vendor Array ==" + vendorArr[0]);


it returns in alert
vendor Array == Undefined
.
thanks.

Answer

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

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

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;
}).get();