We help IT Professionals succeed at work.

Setting a variable in an index loop over jQuery tabs.

brianmfalls
brianmfalls asked
on
So...  all conditions are met in the code below.  The 'setting abort placement' alert executes, then the abort displaying the definition of the variable executes.  When the loop ends, the alert outside of the loop displays 'not set'.  Why!?!?!?!  It's maddening.  Shouldn't the second and third alert show the same value???  What am I missing?  TIA!  :)

var abortPlacement = 'not set';

$("#ajaxContainer .ui-droppable").each(function() { // loop through all droppable areas
	var dropContainerID = '#' + this.id; // this is the ID of the container being indexed in the loop, which will be compared to droppableAreaID 
	var containerContent = $(dropContainerID).formhtml();  // this is the content of the container being indexed in the loop
	if (containerContent.indexOf('detailpage') >= 1) { // if coupon exists in content of container being indexed
		alert('setting abort placement');
		var abortPlacement = dropContainerID;
		alert('abortPlacement 1: ' + abortPlacement);
	}
});

alert('abortPlacement 2: ' + abortPlacement);

Open in new window

Comment
Watch Question

Line 8: get rid of 'var'
Kyle HamiltonData Scientist
Most Valuable Expert 2014

Commented:
the abortPlacement var is specific to "each" .ui-droppable in the #ajaxContainer, so in the function it knows what it's referring to. Outside the function, there is no reference.

Try adding  a return statement if you want to access the value of the abortPlacement  outside the function.

Although, if there is more than one abortPlacement, I think it'll give you the values for "each" .ui-droppable.

But why do you need it to be set outside of the loop? Is the function not working?

(my explanation is not in technical terms, sorry, I hope it makes sense)

var abortPlacement = 'not set';

$("#ajaxContainer .ui-droppable").each(function() { // loop through all droppable areas
        var dropContainerID = '#' + this.id; // this is the ID of the container being indexed in the loop, which will be compared to droppableAreaID 
        var containerContent = $(dropContainerID).formhtml();  // this is the content of the container being indexed in the loop
        if (containerContent.indexOf('detailpage') >= 1) { // if coupon exists in content of container being indexed
                alert('setting abort placement');
                var abortPlacement = dropContainerID;
                alert('abortPlacement 1: ' + abortPlacement);
        }
return abortPlacement;
});

alert('abortPlacement 2: ' + abortPlacement);

Open in new window

Kyle HamiltonData Scientist
Most Valuable Expert 2014

Commented:
Ignore my comment. zappafan2k2 is totally right. It's cause you were re-declaring the variable, so in essence it was a brand new variable even though it had the same name. Cheers.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.