Reputation: 469
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>
Upvotes: 3
Views: 23937
Reputation: 469
okay I figured the problem. I was trying to alert it when the page loads. script was running when the page starts. but I put the alert in a function and give it as an onclick, then the problem is over now. Thanks for helps
Upvotes: 0
Reputation: 2720
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();
Upvotes: 6
Reputation: 544
try this :
var _ddl = $("[id$='_ddlWorkHourFact']").attr("id");
_option = "#" + _ddl + " option:selected";
_value= $(_option).val();
Upvotes: 1
Reputation: 18588
try something like
$('#ddlWorkHourFact').options[$('#ddlWorkHourFact').selectedIndex].val();
Upvotes: 1
Reputation: 12713
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.
Upvotes: 14
Reputation: 1857
try $('#ddlWorkHourFact :selected').val()
seems like you are missing the hash "#" symbol...
Upvotes: 5