Getting the selected value from dropdownlist in asp.net

23,893

Solution 1

First, make sure that the ID ddlWorkHourFact exists in the HTML code. ASP.NET often creates something like this: ctl1_ddlWorkHourFact. You can use

ClientIDMode="Static"

to avoid that problem. Afterwards

$('#ddlWorkHourFact').val()

should be enough.

Solution 2

Ktt,

You need to understand that ASP.NET will generate a different ID in client-side if you are putting the control inside a content, etc. This is done because the ID in client-side should be unique. If you are using ASP.NET 4.0 you can do what Remy told you.

If you are not using ASP.NET 4.0, you can't do that, but you can do a "workaround" in jquery.

function GetClientID(id, context) {
var el = $("#" + id, context);
if (el.length < 1)
el = $("[id$=_" + id + "]", context);
return el;
}

For more information on this code you can go here.

Then, you only need to do something like: GetClientID("txtboxId").attr("id") to get the ID.

$("#" + GetClientID("ddlWorkHourFact").attr("id") + " option:selected").val();

This is only a example, you can improve the code.

Edit:

You can also use something like this, if you are doing that in same page of control.

$('#<%= ddlWorkHourFact.ClientID %> option:selected').val();

Solution 3

try $('#ddlWorkHourFact :selected').val()

seems like you are missing the hash "#" symbol...

Solution 4

try this :

   var _ddl = $("[id$='_ddlWorkHourFact']").attr("id");
    _option = "#" + _ddl + " option:selected";
    _value= $(_option).val();

Solution 5

try something like

$('#ddlWorkHourFact').options[$('#ddlWorkHourFact').selectedIndex].val();
Share:
23,893
Ktt
Author by

Ktt

Updated on September 24, 2020

Comments

  • Ktt
    Ktt almost 4 years

    I have been trying to get the selected item value from a dropdownlist but it seems like it is not going to work. I have looked at the other topics and I know that this question has been asked several times, but I need help. I have tried the following code:

    $('ddlWorkHourFact option:selected').val()
    

    but it returns me "undefined" and I don't know why.

    Here is my dropdownlist:

    <asp:DropDownList ID="ddlWorkHourFact"  runat="server">
                                <asp:ListItem Value="7" Text="7">7</asp:ListItem>
                                <asp:ListItem Value="8" Selected="True" Text="8">8</asp:ListItem>
                                <asp:ListItem Value="9" Text="9">9</asp:ListItem>
                            </asp:DropDownList>