Richard Testani
Richard Testani

Reputation: 1482

For loop issue in FireFox

Im working on a script which removes the default values in form elements using Prototype and LightView. The scripts works fine in Safari, but not at all in FireFox (3.5.5).

This fires when a lightview is triggered.

document.observe('lightview:opened', function() {
            if($('contact_form')) {
                var defaults = new Array();
                var ins = $('contact_form').getElements();
                var inlen = ins.length;
                for(i=0; i < inlen; i++) {
                    alert(i)
                    if($(ins[i]).readAttribute('type') != 'image') {
                        defaults[ins[i].name] = $(ins[i]).value;
                        $(ins[i]).observe('focus', checkDefault.bind(event, ins[i]));

                    }

                }

                function checkDefault(name, event) {
                    alert(name.name)
                    if($(name).value == defaults[name.name]) {
                        alert(defaults[name.name])
                        $(name).value = '';
                    }
                }
        }
        });

The strange this is, when I check for the length of inlen the proper number is alerted, but when I alert 'i', only the first number is alerted. I can't figure out why this is happening.

Any ideas what's wrong here?

Here is the address of the problem: http://bearing.krd-design.net/

Thanks Rich

Upvotes: 0

Views: 705

Answers (3)

jonycheung
jonycheung

Reputation: 850

First of all, I think it is only going to i=0 is probably because the JS broke during the first iteration. To troubleshoot, I'd put alert() in between lines and see which line is breaking it.

My guess of the problem should be in the line:

$(ins[i]).observe('focus', checkDefault.bind(event, ins[i]));

The first parameter of the 'bind' function should be context and you are passing in 'event'. 'event' isn't defined and it should be the context or scope.

In your case, I think you can just use:

$(ins[i]).observe('focus', checkDefault(ins[i]));

Upvotes: 0

Joel
Joel

Reputation: 19368

I'm not sure if this would cause that problem, but you are missing var:

for(var i=0; i < inlen; i++) {

Also, there are no semi-colon's after any of your alert()s.

Try correcting those, and see if it makes a difference.

EDIT:

As pointed out by Matt, in the comments: neglecting var creates the variable in the global scope. This could cause a problem if prototypejs also uses a global variable i (but I sincerely doubt that).

EDIT 2:

Another possibility is the array accessing by input name:

defaults[ins[i].name] = $(ins[i]).value;

Try declaring defaults as an object:

var defaults = {};

Upvotes: 2

Upperstage
Upperstage

Reputation: 3757

It sounds like a timing issue; the alerts slow execution to the point where your code works in FF. Do you use FireBug?

Upvotes: 1

Related Questions