Javascript Scope Oddity

Stupid problem I had to deal with today.  One program I am developing is a dynamic XML form tool, and one of it’s features is the ability to incorporate dependencies, only show this question if questionA was set to true, and questionB was set to 5, or questionC was set to “cookies”, etc etc, you get the idea.  The dependency code is triggered by onBlur() events on each element.

This was fine when filling out a form, but when you wanted to view a form that had already been filled out, certain answers would not appear because by default, they were not visible.  Now, this problem could have been solved a few ways, but what I felt would be easiest would be just to go through all the form elements and call the onBlur() event on each one.  I used the following code:

for (i = 0; i < document.forms[0].elements.length; i++) 
{  
    if (typeof(document.forms[0].elements[i].onblur) == 'function')
    { 
        document.forms[0].elements[i].onblur(); 
    }  
}

Fairly straightforward.  I then used

Page.RegisterStartupScript()

in my code behind to allow the javascript code to run when the page is loaded.

Funny thing happened though.  Only one onBlur() event would occur.  It’s like the others got stuck in a queue that never fired.  This seemed like such a stupid problem, but i spent a long time trying to figure out what was happening.

What I eventually discovered, was that in my doDependencies javascript code, which performed the show/hide logic on form elements that depended on others, I also used index variable i to loop through various form elements.  When I changed the name of my loop index variable, it worked fine.  I’m still not quite sure why this was even a problem, I would have thought that once you entered the onBlur() function, that the scope would be different and you would be able to re-use the same variable.  Strange.

Advertisements

0 Responses to “Javascript Scope Oddity”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: