Check/uncheck checkboxes in Asp.net GridView using jQuery
In this post, find jQuery code to
- Check/uncheck all child checkbox based on parent checkbox status.
- Update parent checkbox status based on child checkbox status.
Also Read:
How to do it?
- Bind the click event to parent checkbox of ASP.NET GridView.
$('#gdRows').find('input:checkbox[id$="chkParent"]').click( function() { });
- In the click event, based on the parent checkbox status set the child checkbox status.
var isChecked = $(this).prop("checked"); $("#gdRows [id*=chkSelect]:checkbox").prop('checked',isChecked);
- So the complete code for parent checkbox click event is,
$('#gdRows').find('input:checkbox[id$="chkParent"]').click( function() { var isChecked = $(this).prop("checked"); $("#gdRows [id*=chkSelect]:checkbox").prop('checked',isChecked); });
- Now, based on the child checkbox status also need to update the parent checkbox. For example, if out of all the child checkboxes, one is unchecked then parent checkbox should also be checked.So for this, attach an click event handler to all the child checkboxes of ASP.NET GridView.
$('#gdRows').find('input:checkbox[id$="chkSelect"]').click(function() { });
- In this event, first define a flag with true value. And then loop through all the child checkbox and if one of the child checkbox is unchecked then set the flag value to false. And then update parent checkbox status value based on the flag variable value.
var flag = true; $("#gdRows [id*=chkSelect]:checkbox").each(function() { if ($(this).prop("checked") == false) flag = false; }); $("#gdRows [id*=chkParent]:checkbox").prop('checked', flag);
So putting it together the complete jQuery code is,
$(document).ready(function() { $('#gdRows').find('input:checkbox[id$="chkParent"]').click(function() { var isChecked = $(this).prop("checked"); $("#gdRows [id*=chkSelect]:checkbox").prop('checked', isChecked); }); $('#gdRows').find('input:checkbox[id$="chkSelect"]').click(function() { var flag = true; $("#gdRows [id*=chkSelect]:checkbox").each(function() { if ($(this).prop("checked") == false) flag = false; }); $("#gdRows [id*=chkParent]:checkbox").prop('checked', flag); }); });?
See result below
Feel free to contact me for any help related to jQuery, I will gladly help you.