Checking checkboxes

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Checking checkboxes

Post by s.dot »

Interesting how I've forgotten this. :(

I've got a form that allows for deletion of multiple comments.

In my HTML, it looks like this..

Code: Select all

<input type="checkbox" name="cdelete[18]">
<input type="checkbox" name="cdelete[19]">
<input type="checkbox" name="cdelete[20]">
How would I use javascript to check all of the cdelete[*] boxes?

I can do it fine if the name was just cdelete.. but then I couldn't process multiple checked items.

My current javascript looks like this:

Code: Select all

function checkAll()
{
	var cd = document.cdeleteform.cdelete;
	if (cd.length)
	{
		for (i=0; i<cd.length; i++)
		{
			cd[i].checked = true;
		}
	}
}
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Checking checkboxes

Post by superdezign »

Code: Select all

function checkAll() {
  var cd = document.cdeleteform.elements["cdelete[]"];
  for (var i in cd) cd[i].checked = true;
}
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Checking checkboxes

Post by s.dot »

This did not work.. I alert()'d "cd" and it comes up as undefined

Code: Select all

var cd = document.cdeleteform.elements["cdelete[]"];
alert(cd);
cdeleteform is the name of my form
cdelete is the name of the checkboxes although they have a number in them.. eg cdelete[18]
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Checking checkboxes

Post by s.dot »

This works though..

Code: Select all

function checkAll()
{
	var cd = document.cdeleteform.elements;
	
	for (i=0; i<cd.length; i++)
	{
		if (cd[i].type == 'checkbox')
		{
			cd[i].checked = true;
		}
	}
}
Thanks for turning me on to the .elements part.. I was not aware of that.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply