简体   繁体   中英

how to validate if nothing is selected from drop-down using JavaScript

I am trying to validate if nothing is selected from drop-down then i want to show a message to remind users to select something from the drop-down. I have tried this code but it is not working so not sure what am i doing wrong here. here is my code: here is my button in aspx in the gridview:

<FooterStyle HorizontalAlign="Right" />
     <FooterTemplate>
        <asp:Button ID="ButtonAdd" runat="server" Text="Add" OnClick="ButtonAdd_Click"   OnClientClick="return Validate();"  />
         </FooterTemplate>
        </asp:TemplateField>

here is my javascript

<script type="text/javascript">
  function Validate() {
   if (document.getElementById("ddlProject").value == "") {
       alert("Please select value"); // prompt user
       document.getElementById("ddlProject").focus(); //set focus back to control
        return false;
         }
       }

   </script> 

Don't use your drop down lists .net ID in javascript. Use its ClientID:

document.getElementById("<%=ddlProject.ClientID%>")

When asp.net renders the html equivalent of your controls, it doesn't always keep the id the same.

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