How to select all checkboxes in a table by clicking header checkbox

0 votes
I want to select all checkboxes in table by clicking header checkbox and it must deselect all while uncheck.

Any example will help.
asked Feb 1, 2013 by inquirer (710 points)
    

1 Answer

0 votes
 
Best answer

Here is simple example how to select and unselect all checkboxes by clicking header checkbox. Hope this might be helpful.

 

<table align="center" id="results">
<tr>
<th><input type="checkbox" id="header-check" /></th>
<th>Website</th>
<th>Domain</th>
<th>Rank</th>
</tr>
<tr>
<td><input type="checkbox" name="domains[]" value="google.com" /></td>
<td>Google</td>
<td>google.com</td>
<td>1</td>
</tr>
<tr>
<td><input type="checkbox" name="domains[]" value="facebook.com" /></td>
<td>Facebook</td>
<td>facebook.com</td>
<td>2</td>
</tr>
<tr>
<td><input type="checkbox" name="domains[]" value="youtube.com" /></td>
<td>YouTube</td>
<td>youtube.com</td>
<td>3</td>
</tr>
<tr>
<td><input type="checkbox" name="domains[]" value="yahoo.com" /></td>
<td>Yahoo!</td>
<td>yahoo.com</td>
<td>4</td>
</tr>
<tr>
<td><input type="checkbox" name="domains[]" value="baidu.com" /></td>
<td>Baidu.com</td>
<td>baidu.com</td>
<td>5</td>
</tr>
<tr>
<td><input type="checkbox" name="domains[]" value="wikipedia.org" /></td>
<td>Wikipedia</td>
<td>wikipedia.org</td>
<td>6</td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#header-check").on('change', function() {
if ($("#header-check").attr('checked'))
$("#results input[type='checkbox']").attr('checked', true);
else
$("#results input[type='checkbox']").removeAttr('checked');
});
});
</script>
answered Feb 1, 2013 by analyst (3,200 points)
selected Feb 1, 2013 by inquirer
...