check all checkboxes in form with a click

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
User avatar
wmasterj
Forum Commoner
Posts: 40
Joined: Mon Aug 18, 2003 5:52 pm
Location: Stockholm, Sweden

check all checkboxes in form with a click

Post by wmasterj »

this piece of code aint mine but was horryfing to find so i thought i just post with easier words and again so people easier find it:

Code: Select all

<script language=&quote;Javascript&quote;> 

<!--	Checks and unchecks all checkboxes in form		-->
<!--	Use:							-->
<!--		<form>						-->
<!--		...						-->
<!--		<input type=checkbox,submit ... onClick=&quote;toggelAll(this)&quote;>-->
<!--		...						-->
<!--		</form>						-->

function toggleAll(toggleBox) { 
	
	var currForm = toggleBox.form; 
	var isChecked = toggleBox.checked; 
	for (var elementIdx=0; elementIdx<currForm.elements.length; elementIdx++) { 

		if (currForm.elements&#1111;elementIdx].type == 'checkbox') { 

			currForm.elements&#1111;elementIdx].checked = isChecked; 
		} 
	} 
} 


</script>
The author posted it here:
viewtopic.php?t=1479
The Monkey
Forum Contributor
Posts: 168
Joined: Tue Mar 09, 2004 9:05 am
Location: Arkansas, USA

Post by The Monkey »

If you would prefer to have Check all :: Uncheck all links, instead of a toggle, you may use this code (Stolen from phpBB Olympus, but it is hardly complicated enough to warrant a disclaimer, imo...):

Code: Select all

function marklist(form_name, status)
{
	for (i = 0; i < document.forms&#1111;form_name].length; i++)
	{
		document.forms&#1111;form_name].elements&#1111;i].checked = status;
	}
}
Call like such:

Code: Select all

<a href=&quote;javascript:marklist('nameofyourform', true)&quote;>Mark All</a> :: 
<a href=&quote;javascript:marklist('nameofyourform', false)&quote;>Unmark All</a>
- Monkey
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it helps to know the name of the element you wish to toggle, iterating blindly through the form's element array can lead to you adding the checked property to several objects which don't need it (type checking helps)
Post Reply