8

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');
    }
});
James Johnson
  • 45,496
  • 8
  • 73
  • 110
Bitmask
  • 918
  • 2
  • 11
  • 22

2 Answers2

14

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.

James Johnson
  • 45,496
  • 8
  • 73
  • 110
  • 1
    Wouldnt this just get the selected value? – Bitmask Sep 15 '11 at 21:03
  • The "if ($("input[@name=GroupName]:checked").val() == "IS")" is to compare if the selected RadioButton has value "IS" The value of ddl is to be changed based on the radiobutton – Bitmask Sep 15 '11 at 21:13
  • Note* You also have to worry about the currently selected option first. You will run into a server error if 2 options have selected set to true on a data bound drop down list. – Ben Sewards Dec 20 '12 at 19:21
  • I'm not 100% positive of this, but I don't think so. Since we're setting the selected value in client script with jQuery, I believe the previously selected item will be deselected as part of that process. I've used this technique before, and I don't recall any server errors ever occurring. – James Johnson Dec 22 '12 at 02:28
3

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.

Renjith Thomas
  • 147
  • 1
  • 4