Tag Archives: HTML

jQuery Child Inheritance

See the DEMO

This is one of my favorite examples of how versatile jQuery is. A complex requirement made simple with child inheritance.

Recently, I was asked to make a none of the above option for a checklist. Basically, if any of the options were checked, “None of the above” would remain unchecked. If “None of the above” where checked, it would deselect previously selected options.

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html lang="en">
	<head>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
	</head>
 
	<body>
		<script type="text/javascript">
			$(document).ready(function() {
				$('#nota_wrapper').delegate("input", "click", function() {
					if ($(this).attr('id') != 'nota') {
						$('#nota').attr('checked',false);	
					} else {
						$(this).closest('#nota_wrapper').find('input:checkbox').attr('checked',false);
						$('#nota').attr('checked',true);					
					} 
				});
			});
		</script>
 
		<form action="test.html" method="post">
			<div id="nota_wrapper">
				<input type="checkbox" name="child[]" id="ch1" value="1" /> <label for="ch1">Child 1</label><br />
				<input type="checkbox" name="child[]" id="ch2" value="2" /> <label for="ch2">Child 2</label><br />
				<input type="checkbox" name="child[]" id="ch3" value="3" /> <label for="ch3">Child 3</label><br />
				<input type="checkbox" name="child[]" id="ch4" value="4" /> <label for="ch4">Child 4</label><br />
				<input type="checkbox" name="child[]" id="nota" value="n" /> <label for="nota">None of the Above</label><br />
			</div>
			<input type="submit" value="submit" />
		</form>	
	</body>
</html>

As you can see. It’s pretty straight forward. All of the checkboxes exist as elements within the nota_wrapper div. That id could have just as easily been assigned to the form or to a wrapper around the form. We then simply delegate the click function to the nota_wrapper. When a click event occurs, it looks to see if anything other than the nota checkbox was clicked. If it was, it sets the nota element checked value to false.

If the nota element WAS checked, it removes any checked values from and of the other child checkbox elements.

See the DEMO