使用 JQuery 从 .NET 下拉列表中获取选定的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6059240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting selected value from .NET dropdown using JQuery
提问by user517406
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 :
我试图在 JQuery 中获取 .NET 下拉列表的值,但我只能获取所选项目的 ID,而不是所选值。是否有可能做到这一点?这是我当前的代码,它获取所选项目的 ID:
alert($('#<%=ddlReportPeriods.ClientID %>').val());
回答by Devjosh
try
尝试
alert($('#<%=ddlReportPeriods.ClientID %> option:selected').text());
回答by Firnas
You can set an attribute of ASP.NET control which will not change the ID at run time, that is
你可以设置一个ASP.NET控件在运行时不会改变ID的属性,即
ClientIDMode = "Static"
Then try,
那就试试吧
alert($("#ddlReportPeriods option:selected").val());
回答by gen
if it's the same as a regular html dropdown box you can try
如果它与常规的 html 下拉框相同,您可以尝试
$('#<%=ddlReportPeriods.ClientID %> option:selected').val()
回答by Rory McCrossan
Try this:
尝试这个:
alert($('#<%=ddlReportPeriods.ClientID %> OPTION:selected').val());
回答by Ahsan Aftab
<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".
这是您可以为下拉列表或文本框或任何其他 asp 控件分配一些值的方式。只是你必须提到“id”。
回答by Pointy
If what you want is the textual content of the currently-selected <option>
tag under your <select>
element, then you could do this:
如果您想要的是元素<option>
下当前选定标签的文本内容<select>
,那么您可以这样做:
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 ...
编辑— 建议使用 ":selected" 限定符的其他答案比这更好......