I am just starting to learn jquery and came up with this bit of code for changing the status of checkboxes.
Can it be improved or is there a better way to achieve the same thing?
The HTML document is generated dynamically so i wouldnt know the names to the Id, classes and element names. The HTML document contains groups of checkboxes. Each group has a master checkbox and a number of child checkboxes.
- When the master checkbox is clicked, all its child checkboxes are checked
- When any child checkbox is clicked, its corresponding master is also checked
- When a child is unchecked, its corresponding master will be unchecked if there is no other checked child in the same group.
This is my first attempt at jquery so please feel free to suggest improvements. I wont be suprised if the same thing can be achieved with a one liner
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<SCRIPT language="javascript">
$(document).ready(function() {
$('input[type=checkbox]').click(function() {
if($(this).attr('name')=='master'){
$('.' + $(this).attr('class')).attr('checked', this.checked);
}
if($(this).attr('name')=='child'){
var childChecked = false;
$('.' + $(this).attr('class')).each(function(){
if (this.checked && this.name=="child"){
childChecked=true;
}
});
if (childChecked==false){
$('.' + $(this).attr('class')).each(function(){
if (this.name=='master'){
this.checked = childChecked;
}
});
}else{
$('.' + $(this).attr('class')).each(function(){
if (this.name=='master'){
this.checked = childChecked;
}
});
}
}
});
});
</script>
<title>Multiple Checkbox Select/Deselect - DEMO</title>
</head>
<body>
<a href="">Link</a>
<H2>Multiple Checkbox Select/Deselect - DEMO</H2>
<table border="1">
<tr>
<th><input type="checkbox" id="masterCheckBox" name="master" class="master1"/></th>
<th>Master</th>
<th>Rating</th>
</tr>
<tr>
<th><input type="checkbox" id="child1" class="master1" name="child"/></th>
<th>Child</th>
<th>Rating</th>
</tr>
<tr>
<th><input type="checkbox" id="child1" class="master1" name="child"/></th>
<th>Child</th>
<th>Rating</th>
</tr>
</table>
<table border="1">
<tr>
<th><input type="checkbox" id="masterCheckBox" name="master" class="master2"/></th>
<th>Master</th>
<th>Rating</th>
</tr>
<tr>
<th><input type="checkbox" id="child1" class="master2" name="child"/></th>
<th>Child</th>
<th>Rating</th>
</tr>
<tr>
<th><input type="checkbox" id="child1" class="master2" name="child"/></th>
<th>Child</th>
<th>Rating</th>
</tr>
</table>
</BODY>
</HTML>