Invert checkbox selection

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Invert checkbox selection

Post 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
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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>
evilMind
Forum Contributor
Posts: 145
Joined: Fri Sep 19, 2003 10:09 am
Location: Earth

Post 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>
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

Thanks guys, worked a treat (went for evilMinds sample).

Mark
Post Reply