tabs

Wednesday, November 13, 2013

Validate DropdownList using jQuery

"This post is all about how to validate DropdownList using jQuery".
DropdownList is one of the common fields we use in all kind of web forms in almost every web application. It is common to apply validations on certain fields in all web forms. Here in this post we are going to see how to validate DropdownList using jQuery.
Here in our case, I am using a simple Webform with a DropdownList and a button. The DropdownList has a collection of categories, if the user doesn’t select a category an alert event fires up saying the user to choose a category.


In order to do this the following code is to be followed.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
  </script>
  <script type="text/javascript">
        $(document).ready(function () {
            $('#btnCheck').click(function () {
                if ($("#ddlCategory").val() > 0) {
                    return true;
                }
                else {
                    alert('Please choose a category')
                    return false;
                }
            })
        });
 
    </script>
</head>
<body>
    <form id="myForm" runat="server">
        <div>
            <b>Selected Category:</b>
            <asp:DropDownList ID="ddlCategory" runat="server">
                <asp:ListItem Text="--Choose--" Value="0" />
                <asp:ListItem Text="Education" Value="1" />
                <asp:ListItem Text="Sports" Value="2" />
                <asp:ListItem Text="Entertainment" Value="3" />
                <asp:ListItem Text="Business" Value="4" />
                <asp:ListItem Text="Trading" Value="5" />
            </asp:DropDownList>
            <asp:Button ID="btnCheck" Text="Check" runat="server" />
        </div>
    </form>
</body>
</html>

This is how you validate a DropdowlList using jQuery.Hope this post helps you and feel free to post your suggestions and comments on it.
For more posts on jQuery click jquery tricks

No comments:

Post a Comment