Page 1 of 1
Invert checkbox selection
Posted: Tue Oct 21, 2003 9:00 am
by JayBird
I have a page that is dynamically generated with an unknown number of check boxes.
i need to be able to select a number of the check boxes and then be able to click a button and invert the selection (uncheck the checked boxes and check the unchecked one).
How would i go about doing this, not forgetting you don't know how many check boxes are going to be generated.
Thanks
Mark
Posted: Tue Oct 21, 2003 10:08 am
by volka
you might iterate through the set of child nodes of a parent-container of some sort
Code: Select all
<html>
<head>
<script>
function addCheckbox(oParent)
{
oNewInput = document.createElement("input");
oNewInput.type="checkbox";
oParent.appendChild(oNewInput);
}
function toggleCheckboxes(oParent)
{
for (oChild = oParent.firstChild; oChild != null; oChild=oChild.nextSibling)
{
if(oChild.tagName!=null && oChild.tagName=="INPUT" && oChild.type=="checkbox")
{ oChild.checked = !oChild.checked; }
}
}
</script>
</head>
<body>
<div id="checkboxes" style="border: 1px solid black">
<input type="checkbox" />
</div>
<button onClick="javascript:addCheckbox(document.getElementById('checkboxes'));">
add checkbox
</button>
<button onClick="javascript:toggleCheckboxes(document.getElementById('checkboxes'))">
toggle checkboxes
</button>
</body>
</html>
Posted: Tue Oct 21, 2003 12:24 pm
by evilMind
also could do:
Code: Select all
function ToggleCheckbox() {
for (var i = 0; i < document.formName.elements.length; i++) {
if(document.formName.elementsїi].type == 'checkbox'){
document.formName.elementsїi].checked = !(document.formName.elementsїi].checked);
// The !(document... will invert the current value of the checkbox giving you the results you desire
}
}
}
in the html part you would then call by:
Code: Select all
<a onclick="ToggleCheckbox()" href="javascript:void(0)">Toggle All</a>
Posted: Wed Oct 22, 2003 3:23 am
by JayBird
Thanks guys, worked a treat (went for evilMinds sample).
Mark