NemoPS
NemoPS

Reputation: 411

jQuery - variable defined inside $.each, but it's undefined outside

I have the following code, which is driving me nuts:

$.each(originalSteps, function() {
                    if($(this).attr('id') == 'ps_attributes_step_'+(parseInt(triggered_step)+1))
                    {
                        alert('testing validity');
                        var newOne = $(this);
                    }
                });
                console.log(newOne)

Now, the alert is being triggered, but newOne is undefined outside the loop. Any Solution to this?

Thanks

Upvotes: 0

Views: 1602

Answers (1)

Ravi Y
Ravi Y

Reputation: 4376

That is becuase you have declared the variable inside. Change your code as below.

var newOne;
$.each(originalSteps, function() {
    if($(this).attr('id') == 'ps_attributes_step_'+(parseInt(triggered_step)+1))
    {
        alert('testing validity');
        newOne = $(this);
        return false;
    }
});

console.log(newOne);

Edited to add return false. See comment below for explanation.

Upvotes: 2

Related Questions