Save DropDownList value into a javascript variabale

1.4k Views Asked by At

I am relatively new to C#, and I have been researching this across the internet for a few days now. I need the value selected in asp.net DropDownList to be declared as a JavaScript variable. I have looked into <asp:hiddenfield>'s mostly, but I'm not sure if this is the best option to go down. So I have two questions:

  1. Are <asp:hiddenfield>'s the best option?
  2. How do you declare a C# string into a javascript variable?

    <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"/> 
    
3

There are 3 best solutions below

0
On
<script type="text/javascript">
    var serverDropdown = document.getElementById('dropDownID');
    var reasonIndex = serverDropdown.selectedIndex;
    var reasonValue = serverDropdown.value;
</script>
2
On

Change this <asp:DropDownList runat="server" ID="dropDownID"> to this:

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

and then use this JavaScript to get the value:

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

To store dropdownlist value in javascript variable, there is no need to use hidden field,

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.

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