简体   繁体   English

将DropDownList值保存到javascript变量中

[英]Save DropDownList value into a javascript variabale

I am relatively new to C#, and I have been researching this across the internet for a few days now. 我是C#的新手,现在已经在互联网上进行了几天的研究。 I need the value selected in asp.net DropDownList to be declared as a JavaScript variable. 我需要在asp.net DropDownList中选择的值声明为JavaScript变量。 I have looked into <asp:hiddenfield> 's mostly, but I'm not sure if this is the best option to go down. 我主要研究了<asp:hiddenfield> ,但是我不确定这是否是最好的选择。 So I have two questions: 所以我有两个问题:

  1. Are <asp:hiddenfield> 's the best option? <asp:hiddenfield>的最佳选择吗?
  2. How do you declare a C# string into a javascript variable? 如何在JavaScript变量中声明C#字符串?

     <asp:DropDownList runat="server" ID="dropDownID"> <asp:ListItem Text="-- Select Reason --" Value=""></asp:ListItem> <asp:ListItem Text="Booking" Value="1"></asp:ListItem> <asp:ListItem Text="Discussing" Value="2"></asp:ListItem> <asp:ListItem Text="Quotation" Value="3"></asp:ListItem> </asp:DropDownList> <asp:hiddenfield ID="valueInHiddenField" value="" runat="server"/> 
<script type="text/javascript">
    var serverDropdown = document.getElementById('dropDownID');
    var reasonIndex = serverDropdown.selectedIndex;
    var reasonValue = serverDropdown.value;
</script>

Change this <asp:DropDownList runat="server" ID="dropDownID"> to this: 将此<asp:DropDownList runat="server" ID="dropDownID">更改为此:

<asp:DropDownList runat="server" ID="dropDownID" ClientIDMode="Static">

and then use this JavaScript to get the value: 然后使用以下JavaScript获取值:

var val = document.getElementById('dropDownID').value;

To store dropdownlist value in javascript variable, there is no need to use hidden field, 要将dropdownlist值存储在javascript变量中,无需使用隐藏字段,

try this... 尝试这个...

 <script type="text/javascript">
     var dropdown_value = document.getElementById('<%=dropDownID.ClientID%>').value;
 </script>

here instead of dropdownID we have to use its ClientID.....In asp.net 4.0 you can direclty use its id by doing ClientIDMode="Static" of the dropdown. 在这里,而不是dropdownID,我们必须使用其ClientID。.....在asp.net 4.0中,您可以通过执行下拉菜单的ClientIDMode =“ Static”来直接使用其ID。

     var dropdown_value = document.getElementById('dropDownID').value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM