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)
			&#123;
				oNewInput = document.createElement("input");
				oNewInput.type="checkbox";
				oParent.appendChild(oNewInput);
			&#125;
			
			function toggleCheckboxes(oParent)
			&#123;
				for (oChild = oParent.firstChild; oChild != null; oChild=oChild.nextSibling)
				&#123;
					if(oChild.tagName!=null && oChild.tagName=="INPUT" && oChild.type=="checkbox")
					&#123;	oChild.checked = !oChild.checked; &#125;
				&#125;
			&#125;
		</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() &#123;
  for (var i = 0; i < document.formName.elements.length; i++) &#123;
    if(document.formName.elements&#1111;i].type == 'checkbox')&#123;
      document.formName.elements&#1111;i].checked = !(document.formName.elements&#1111;i].checked);
    // The !(document... will invert the current value of the checkbox giving you the results you desire
    &#125;
  &#125;
&#125;
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