Tuesday, September 17, 2013

check whether checkbox is checked or not in Jquery Asp.net | validate checkbox using Jquery

hi in this post i will show how to validate a checkbox in Jquery.

Example :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    SELECT Laptops:
    <br />
        <asp:CheckBox ID="CheckBox1" Text="HP" runat="server" /><br />
        <asp:CheckBox ID="CheckBox2" Text="DELL" runat="server" /><br />
        <asp:CheckBox ID="CheckBox3" Text="ACER" runat="server" /><br /><br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </div>
    </form>
</body>
</html>

1. to check atleast one checkbox should be checked from the list of checkboxes

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('input[id$=btnSubmit]').click(function (e) {
            var checked = $(':checkbox:checked').length; //checks whether atleast one check box is checked from the list of checkboxs.
            if (checked == 0) {
                alert('Select atleast one checkbox');
                e.preventDefault();
            }
            else {
                alert('all validations true');
            }
        });
    });
</script>


2. to validate a specific checkbox 

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('input[id$=btnSubmit]').click(function (e) {
            var checked = $('#CheckBox1').is(':checked'); // for a specific checkbox
            if (checked == 0) {
                alert('First Checkbox Should be checked');
                e.preventDefault();
            }
            else {
                alert('all validations true');
            }
        });
    });
</script>

No comments:

Post a Comment