Luis
Luis

Reputation: 1097

`For loop` stays in 0

I'm having a loop problem. It doesn't increase the 'i' value from 0. Can you help me?

Here's my code:

var users = ["a", "b", "c"];

if (users.length > 0) {
    $(".ajax").live("submit", function(){
        for (var i=0; i < users.length; i++) {
            console.log(i);

            var forma = $(this);

            $("input[name=_session]", forma).val(users[i]);

            ajaxy(forma, function(data){
                console.log(data.status);
            });

            return false;
        }
    });
} else...

Upvotes: 0

Views: 303

Answers (3)

Wizsplat
Wizsplat

Reputation: 21

Because you return on the first iteration of the loop, methinks.

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49803

The return statement in the for loop is causing it to exit before it can get to the next iteration.

Upvotes: 3

sachleen
sachleen

Reputation: 31131

You return false after the first iteration of the loop. I think you need to move the return false; line out of the loop block.

Properly indenting your code will make errors like this obvious:

if (users.length > 0) {
    $(".ajax").live("submit", function () {
        for (var i = 0; i < users.length; i++) {
            console.log(i);
            var forma = $(this);
            $("input[name=_session]", forma).val(users[i]);
            ajaxy(forma, function (data) {
                console.log(data.status);
            });
            return false; // This should not be here
        }
    });
}

Upvotes: 10

Related Questions