1

I need to get the value of a variable that's set in an each loop in jQuery. Here's what I have so far:

$('#conservatory_size .eva_toggle').each(function(){
  if($(this).hasClass('active')){
     var conservatory_size_total = $(this).data('price');
  }
});
alert(conservatory_size_total);

The value is there and it works, because if I call the alert inside the each loop it shows the correct price. But out of the loop the variable doesn't even alert.

Any ideas?

UPDATE

If I do what you have said, the IF statement is blatantly working, declaring the variable before the loop.. is not.

$('#conservatory_size .eva_toggle').each(function(){
            if($(this).hasClass('active')){
                var conservatory_size_total = $(this).data('price');
                alert('Has class.');
            }
        });
        alert(conservatory_size_total);

enter image description here

2 Answers 2

1

Declare the variable outside the loop:

var conservatory_size_total = '';
$('#conservatory_size .eva_toggle').each(function(){...
Sign up to request clarification or add additional context in comments.

3 Comments

The value is empty.
Please see my updated question, definitely not that.
Ahhh! I was doing it wrong. Thank you. Have marked this as the answer. Thank you.
0

Try to declare your var outside the loop

var conservatory_size_total;
$('#conservatory_size .eva_toggle').each(function(){
  if($(this).hasClass('active')){
     conservatory_size_total = $(this).data('price');
  }
});
alert(conservatory_size_total);

1 Comment

It just says 'undefined'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.