-1

i am having problem in getting the value of the variable. In the each query loop i am getting the correct calculated value but when i try to get the value outside the each loop then it shows the value as 0 Here is the Code: Updated Code

// Discounts Calculations
        var item_discounts_current = 0;
        $(this).nextUntil("#item-extras-discounts").find('.item-current-discounts :selected').each(function(item_discounts_current) {
            var item_discounts_type = parseFloat( $(this).attr('data-dtype') );
            if ( item_discounts_type == 1 ) {
                item_discounts_current += parseFloat( $(this).attr('data-dvalue') ) + item_discounts_current;
            }
            else {
                var percentage_val = parseFloat( $(this).attr('data-dvalue') ) / 100;
                var new_item_discount_value = item_total_price_current * percentage_val;
                item_discounts_current += item_discounts_current + new_item_discount_value;
            }
            // This is showing calculated value
            console.log(item_discounts_current);
        });
        // This is showing 0 value
        console.log(item_discounts_current);

1 Answers1

3

With var item_discounts_current inside the each loop you are creating a new local variable instead of using the global variable. Remove the var to use the global variable.

Here you can read about the scope of variables in JavaScript.

Community
  • 1
  • 1
Carlos Mayo
  • 2,054
  • 1
  • 19
  • 35
  • I have removed var but still i am getting 0 value see my updated Question – Shahnawaz Ali Nov 04 '15 at 12:07
  • Remove the `item_discounts_current` from `function(item_discounts_current)` in the each function. You are declarating a parameter with the same name of a global var – Carlos Mayo Nov 04 '15 at 12:09