HI WELCOME TO SIRIS

Part 66 - Check uncheck all checkboxes with another single checkbox using jquery

Leave a Comment
we will discuss, how to check/uncheck all checkboxes with another single checkbox using jquery in an asp.net mvc application. 

We want the output as shown below
Check uncheck all checkboxes using jquery



Here is the requirement
1. When the checkbox in the header is selected, all the checkboxes in the respective rows should be selected. If we deselect any of the checkbox, then the header checkbox should be automatically deselected.
2. When the checkbox in the header is deselected, all the checkboxes in the respective rows should be deselected as well. If we start to select each checkbox in the datarows, and upon selecting checkboxes in all the datarows, the checkbox in the header should be selected.
3. We also need a client side confirmation, on the number of rows to be deleted. The selected rows should be deleted from the database table, only when OK button is clicked. If cancel button is clicked, the form should not be posted to the server, and no rows should be deleted.

Here's the required jQuery script. Please paste this in the "Index.cshtml" view.
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
    $(function () {
        $("#checkAll").click(function () {
            $("input[name='employeeIdsToDelete']").attr("checked"this.checked);

            $("input[name='employeeIdsToDelete']").click(function () {
                if ($("input[name='employeeIdsToDelete']").length == $("input[name='employeeIdsToDelete']:checked").length) {
                    $("#checkAll").attr("checked""checked");
                }
                else {
                    $("#checkAll").removeAttr("checked");
                }
            });

        });
        $("#btnSubmit").click(function () {
            var count = $("input[name='employeeIdsToDelete']:checked").length;
            if (count == 0) {
                alert("No rows selected to delete");
                return false;
            }
            else {
                return confirm(count + " row(s) will be deleted");
            }
        });
    });    
</script>

jQuery file can also be referenced from the following website
jQuery - http://code.jquery.com/jquery-latest.min.js
Google - http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
Microsoft - http://ajax.microsoft.com/ajax/jQuery/jquery-1.9.1.min.js

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.