简体   繁体   中英

Pass dropdownlist value to textbox using javascript

I have a button which when clicked should just pass the selected value from dropdownlist to a textbox.Here is the code :

    <td>
    <script type="text/javascript">
    function calculateCity() {

     var city = document.getElementById('<%= ddlCity.ClientID%>');
     txtCity0.value = city.options[city.selectedIndex].value;
                }
     </script>

     <asp:TextBox ID="txtCity0" runat="server" Width="260px"></asp:TextBox>
     <asp:DropDownList ID="ddlCity" runat="server">
     <asp:ListItem Value="1">Mumbai</asp:ListItem>
     <asp:ListItem Value="2">Pune</asp:ListItem>
     </asp:DropDownList>
     <input id="btnCity" onclick="calculateCity();" type="button" value="Calculate City" /></td>

This code just doesnt do anything.Any help will be appreciated.Thank You

You are finding the drop down correctly, but then not finding the text box and simply trying to use it.

You need a similar getElementById line for the text box

Try this:-

function calculateCity() {
    var city = document.getElementById('<%= ddlCity.ClientID%>');
    document.getElementById('<%= txtCity0.ClientID%>').value = 
                                                city.options[city.selectedIndex].value;
 }

Or if you can use jQuery , then you can do this:-

$("#<%= btnCity.ClientID %>").click(function() {
    $('#<%= txtCity0.ClientID %>').val($('#<%= ddlCity.ClientID %>').val());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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