Monday, July 9, 2012

Validate ASP.NET DropDownList using jQuery

In this small post, today I will show you how to validate ASP.NET DropDown List using jQuery.

Let's declare a DropDownList.
<asp:DropDownList ID="ddlList" runat="server">
   <asp:ListItem Text="Select" Value="0" />
   <asp:ListItem Text="jQuery" Value="1"></asp:ListItem>
   <asp:ListItem Text="JavaScript" Value="2"></asp:ListItem>
   <asp:ListItem Text="Prototype" Value="3"></asp:ListItem>
   <asp:ListItem Text="Dojo" Value="4"></asp:ListItem>
   <asp:ListItem Text="Mootools" Value="5"></asp:ListItem>
</asp:DropDownList>
To validate the dropdown list, all you need to do is to get the selected value and check if it is not 0. If 0, then nothing is selected so alert the user, otherwise proceed.
$(document).ready(function() {
    $('#btnValidateByVal').on('click', function(e) {
        var iVal = $('#ddlList').val();
        if (iVal == 0) 
        {
            alert('Please select any technology.');
            e.preventDefault();
        }
        else 
            alert('Well Done!!!!');
   })
})​
In the above jQuery code, the validation is done using value of the selected item. But you can also validate the dropdown using the selected item text.
$(document).ready(function() {
    $('#btnValidateByText').on('click', function(e) {
        var sText = $('#ddlList1 option:selected').text().toLowerCase();
        if (sText == 'select') 
        {
            alert('Please select any technology.');
            e.preventDefault();
        }
        else 
           alert('Well Done!!!!');
    })
})​
Note: Above both jQuery codes will work only with jQuery 1.7 or higher version as I have used .on() method to bind the click event and .on was introduced in jQuery 1.7. So if you are using below version then you can either .live() or .bind() method.

Suggested Post,
Feel free to contact me for any help related to jQuery, I will gladly help you.