...

View Full Version : problem with javascript checkall function



jewishj
03-31-2005, 03:02 AM
I am using the following functions to check checkboxes...



//this is the checkAll function for the checkbox to toggle checked/unchecked
function checkAll(checkboxID){

state=(document.getElementById(checkboxID).checked==false) ? false :true;

i=1;
while(document.getElementById(checkboxID+i)!=false){
document.getElementById(checkboxID+i).checked=state;
i++;
}
}

//this is for the check all links
function checkAllFromLink(checkboxID,state){
i=0;

while(document.getElementById(checkboxID+i)!=false){
document.getElementById(checkboxID+i).checked=state;
i++;
}
}


The first is accessed via a checkbox with an id like "blah" where the set of checkboxes have ids like "blah1" "blah2" "blah3" etc.
A small example of html to access this function:


<input type="checkbox" id="blah" onclick="checkAll('blah')" />
<input type="checkbox" id="blah1" />
<input type="checkbox" id="blah2" />
<input type="checkbox" id="blah3" />



The second is accessed via a link that passes the id of the set of checkboxes (ids work the same as the first) and the state to change the checkbox to.
A small example of html to access this function:


<a href="javascript:checkAllFromLink('blah',true)">Check All</a>
<a href="javascript:checkAllFromLink('blah',false)">Uncheck All</a>
<input type="checkbox" id="blah1" />
<input type="checkbox" id="blah2" />
<input type="checkbox" id="blah3" />


The functions work but still produce errors: "document.getElementById(...) is null or not an object." I cannot reference the checkboxes by name because the names have to be in the form of arrays for submittal.

Thanks for any help with this issue

Kor
04-01-2005, 09:17 AM
I cannot reference the checkboxes by name because the names have to be in the form of arrays for submittal.

This is a wrong presumtion. You may acces the elements by their name as well, but that reference is a collection, so that you need the index as well

document.getElementsByName('blah1')[0]
document.getElementsByName('blah2')[0] and so on

Ok now, you problem:
1. first function

state=(document.getElementById(checkboxID).checked==false)

this is a wrong reference. You have no element with id='blah'

2. both functions

To check wether an object exists, you must use a null value, not a Boolean true/false

while(document.getElementById(checkboxID+i)!=null){

otherwise the increment will rise an extra value looking for a last element which do not exists (id=blah4 in your example)



function checkAllFromLink(checkboxID,state){
var i=1;

while(document.getElementById(checkboxID+i)!=null){
document.getElementById(checkboxID+i).checked=state;
i++;
}
}

glenngv
04-04-2005, 10:57 AM
function checkAllFromLink(checkboxID,state){
var el, i=1;
while (el=document.getElementById(checkboxID+(i++))){
el.checked=state;
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum