19

I am trying to get the value of a .NET dropdown list in JQuery, but I am only able to get the ID of the selected item, not the selected value. Is it possible to do this? This is my current code, which gets the ID of the selected item :

alert($('#<%=ddlReportPeriods.ClientID %>').val());
1
  • 1
    That code does in fact get the value of an element, not the id. Use something like Firebug or a developer console to inspect your actual page. Perhaps you want the text content of the selected <option> in your dropdown, which is not the same thing as the value. Commented May 19, 2011 at 13:20

6 Answers 6

41

try

alert($('#<%=ddlReportPeriods.ClientID %> option:selected').text());
Sign up to request clarification or add additional context in comments.

4 Comments

This was the syntax that worked, though there is a typo, it should read : alert($('#<%=ddlReportPeriods.ClientID %> option:selected').text());
Using client side: $("[id$='ddlReportPeriods'] option:selected").text()
@ Mateusz Migała, yes that is cleaner way if you use the external javascript file.
I found the value (.val()) is what I wanted, not the text. Thus $('#<%=ddlReportPeriods.ClientID %> option:selected').val() is the correct syntax, for my case. If anyone is having issues with pulling the text (.text()), give .val() a try.
7

You can set an attribute of ASP.NET control which will not change the ID at run time, that is

ClientIDMode = "Static"

Then try,

alert($("#ddlReportPeriods option:selected").val());

1 Comment

.val() worked for me, rather than .text(). Thank you.
5

if it's the same as a regular html dropdown box you can try

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

1 Comment

Syntax error, unrecognized expression: #<%=contactStateDDL.ClientID %> option:selected
1

Try this:

alert($('#<%=ddlReportPeriods.ClientID %> OPTION:selected').val());

Comments

0

If what you want is the textual content of the currently-selected <option> tag under your <select> element, then you could do this:

var $sel = $('#<%=ddlReportPeriods.ClientID %>');
alert($($sel.attr('options')[$sel.attr('selectedIndex')).text());

edit — the other answers with suggestions to use the ":selected" qualifier are better than this ...

Comments

0
<asp:DropDownList ID="ddMainMenuList" runat="server" class="form-control">
                        </asp:DropDownList>

$("[id*=ddMainMenuList]").val("SomeValue");

This is the way you can assign some value to dropdown or textbox or any other asp control. Just you have to mention "id".

1 Comment

The question asks for a solution to GET the value, not change it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.