Thursday, December 08, 2005

JAVASCRIPT weirdity...

Ran into an interesting problem while I was using javascript today. I had a dynamically generated group of checkboxes that I wanted to be able to check and uncheck as a group. Was using the checkboxes to denote the emails to be deleted from the list.

Came up with the code given below after much researching from our good old web.


function fnMoveMail()
{
for(i=0;i<document.frmWorkAreaTop.chkDelMail.length;i++)
{
if(document.frmWorkAreaTop.chkDelMail[i].checked==false)
(document.frmWorkAreaTop.chkDelMail[i].checked==true;}
}}"


Was calling it from a link that was something like this :
<a href="javascript:fnMoveMail()">

Things were all well and good, as long as the field that is passed into the function is an array of checkboxes. However, since javascript is a "typeless" language, you can call any method on an object, and depending on how egregarious the error is, the user might never see an error message. In this case, when the dynamically generated group of checkboxes has only one element, document.frmWorkAreaTop.chkDelMail is not an array of checkboxes, and its length attribute doesn't return anything. The for loop is not executed at all, and the box is never checked.

The solution is simple enough, just check the type of object passed in:
if(document.frmWorkAreaTop.chkDelMail.type != 'checkbox')
{
for(i=0;i<document.frmWorkAreaTop.chkDelMail.length;i++)
{
if(document.frmWorkAreaTop.chkDelMail[i].checked==true)
{lChkBxCnt = lChkBxCnt + document.frmWorkAreaTop.chkDelMail[i].value + ",";}
}//end of for
lChkBxCnt = lChkBxCnt.substring(0,lChkBxCnt.length-1);
}//end of if(document.frmWorkAreaTop.chkDelMail.type != 'checkbox')
else
{lChkBxCnt = lChkBxCnt + document.frmWorkAreaTop.chkDelMail.value;}


It makes little sense why one checkbox wouldn't be an array of size 1, but the switch caught me a bit off guard.
Unfortunately, a quick google did not turn anything up for me about the logic.

0 Comments:

Post a Comment

<< Home