Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selected value of DropDownList with jQuery

How do i change the value of the dropdownlist that has its data set via the datasource

ddlContacts.DataSource = Data;
ddlContacts.DataBind();

I have tried this but does not work:

$('#<%= rbDepartment.ClientID %>').change(function() {
    if ($("input[@name=GroupName]:checked").val() == "IS") {
        $('#ddlContactType').val('AM');
    }
});
like image 363
Bitmask Avatar asked Sep 15 '11 20:09

Bitmask


People also ask

How can I set the value of a DropDownList using jQuery?

Use $('select[id="salesrep"]'). val() to retrieve the selected value. Use $('select[id="salesrep"]'). val("john smith") to select a value from dropdown.

How do I change the selected value of a drop down list?

To achieve this feat you can use various methods, two of those methods will be explained below. Used Function: val() function: It sets or returns the value attribute of the selected elements. attr() function: It sets or returns the attributes and values of the selected elements.

How show selected value from database in dropdown using jQuery?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

How set multiple selected values in DropDownList jQuery?

With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.


2 Answers

Give this a shot:

var selectedValue = $("#<%=ddlContacts.ClientID%> option:selected").val();

Just noticed that you're trying to set the value:

$("#<%=ddlContacts.ClientID%>").val("thevalue");

Remember, when dealing with ASP.NET controls on the client side, you have to use the ClientID.

like image 121
James Johnson Avatar answered Oct 17 '22 08:10

James Johnson


I had the same problem of getting the current selected value from a drop down list and setting a new value as selected. Below is the code I used and it is working:

ASP .Net code:

<asp:DropDownList runat="server" ID="ddlVersion" />

Select the currently selected drop down list option using JQuery:

var selectedVersion = $('#<%=ddlVersion.ClientID%> option:selected').text();

To set the selected value in drop down list:

$('#<%=ddlVersion.ClientID%> option:selected').text(currentVersion);

This code is working perfectly fine.

like image 34
Renjith Thomas Avatar answered Oct 17 '22 08:10

Renjith Thomas