I’ve got an unimaginably huge order form that I’m combing through for values and building an array from. Amongst other things, I’ve got some each() iterations that I need to extract values from, appending them to variables that are used afterwards. Problem is that the values are returning undefined, which I think is because they’re being assigned within the loop.
Here’s my logic:
- Declare variables
- loop through each
- assign value to variable
- post to array
My understanding is that the variable declaration outside the function allows me to use it globally. Guess I’m wrong!
Here’s a jsFiddle: http://jsfiddle.net/x7CL6/
Here’s the code:
$('a').click(function(event){
event.preventDefault();
/* Declare Variables */
var test = [],
one,
two,
three,
four,
el,
kind,
val;
/* Loop through each paragraph */
$('section').find('p').each(function(){
el = $(this);
kind = el.attr('class');
val = el.html();
if (val === '1'){
one = val;
} else if (val === '2'){
two = val;
} else if (val === '3'){
three = val;
} else if (val === '4'){
four = val;
}
});
test.push({
one: one,
two: two,
three: three,
four: four
});
console.log(test);
});
A variable is global if its declaration is outside any function. In your case all of your variables are defined inside the click handler function, so all are accessible within it and any nested functions including your
each()callback.If the intention is that each click should add another object to the
testarray then you need to definetestoutside the click handler.The reason your variables are undefined is because your if/else conditions are always false so the variables never get assigned a value. Your
valvariable gets assigned the html content from the current element of the loop, and the html content is never equal to the"1","2", etc., strings that you compare it to.I think you probably intended to compare to each element’s class attribute instead, which you’ve put in the
kindvariable:and so forth: http://jsfiddle.net/x7CL6/4/
…but given that you seem to be processing the elements in document order you could make use of the fact that jQuery passes your
.each()callback the index of the current element:Demo: http://jsfiddle.net/x7CL6/2/
However that still leaves you with an ugly if/else if/… structure that you could avoid like this:
Demo: http://jsfiddle.net/x7CL6/5/