Checkbox Mania
by jacobdubail
HTML
<ul>
<li>
<input type="checkbox" name="tall" id="tall">
<label for="tall">Tall Things</label>
<ul>
<li>
<input type="checkbox" name="tall-1" id="tall-1">
<label for="tall-1">Buildings</label>
</li>
<li>
<input type="checkbox" name="tall-2" id="tall-2">
<label for="tall-2">Giants</label>
<ul>
<li>
<input type="checkbox" name="tall-2-1" id="tall-2-1">
<label for="tall-2-1">Andre</label>
</li>
<li>
<input type="checkbox" name="tall-2-2" id="tall-2-2">
<label for="tall-2-2">Paul Bunyan</label>
</li>
</ul>
</li>
<li>
<input type="checkbox" name="tall-3" id="tall-3">
<label for="tall-3">Two sandwiches</label>
</li>
</ul>
</li>
<li>
<input type="checkbox" name="short" id="short">
<label for="tall">Short Things</label>
<ul>
<li>
<input type="checkbox" name="short-1" id="short-1">
<label for="short-1">Smurfs</label>
</li>
<li>
<input type="checkbox" name="short-2" id="short-2">
<label for="short-2">Mushrooms</label>
</li>
<li>
<input type="checkbox" name="short-3" id="short-3">
<label for="short-3">One Sandwich</label>
</li>
</ul>
</li>
</ul>
CSS
ul {
margin: 5px 20px;
}
li {
margin: 0 0 5px 0;
}
JavaScript
// Apparently click is better chan change? Cuz IE?
$("input[type=checkbox]").click(function() {
var el = $(this);
el
.parent()
.find("ul input[type=checkbox]")
.prop("indeterminate", false)
.prop("checked", el.prop("checked"));
var siblings = el.parent().siblings().add(el.parent());
if (siblings.length > 1) {
var numChecked = 0;
siblings.find("> input[type=checkbox]").each(function(i) {
if ($(this).prop("checked")) {
numChecked++;
}
});
if ((numChecked > 0) && (numChecked < siblings.length)) {
el
.parent().parent().parent()
.find("> input[type=checkbox]")
.prop("indeterminate", true);
} else if (numChecked == 0) {
el
.parent().parent().parent()
.find("> input[type=checkbox]")
.prop("indeterminate", false)
.prop("checked", false);
} else {
el
.parent().parent().parent()
.find("> input[type=checkbox]")
.prop("indeterminate", false)
.prop("checked", true);
}
}
});