3

Hello people here is my code below...

var total = 0;
var find_total;
 function total_val(find_total){

$(find_total).each(function() {
    total += parseInt($(this).text());
    return total;
});

  }

Iam calling this function...

$('#total_price').val(total_val('.price'));

#total_price and .price keeps changing for different div ids and class ... return total; does not work, any ways to fix this??

2
  • You're not returning anything to the outer function. Commented Jun 20, 2014 at 4:28
  • @Friend can you share the html code as well? Commented Jun 20, 2014 at 5:07

2 Answers 2

1

You are returning the total value inside the .each() function, it would not return anything while we expecting a value from the function total_val(),

Try,

function total_val(find_total){ 
   var total = 0; //remove the global variable total and use this.
   $(find_total).each(function() {
    total += parseInt($(this).text());
   });
   return total;
}

or you could use .reduce() to make your code simple.

function total_val(find_total){ 
   return $(find_total).map(function() {
   return parseInt($(this).text());
   }).get().reduce(function(a,b){
   return a+b;
   });
}

Even simpler,

function total_val(find_total){ 
   return $(find_total).get().reduce(function(a,b){
      return a+ parseInt($(b).text(),10);
   },0);
}
Sign up to request clarification or add additional context in comments.

3 Comments

The map and reduce can be done in the same step; see my answer for more details.
ReferenceError: total is not defined (for your first answer)
@maček See here.. jsfiddle.net/L9RJh/1 where did you find the error.? OP has declared the total as global one.. Have you noticed that in his question..?
0

Here's a fiddle showing you a couple ways you can do this.

This could work nicely for you

function total(jq, callback) {
  return jq.get().reduce(function (sum, elem) {
    return sum + window.parseInt(callback(elem), 10);
  }, 0);
}

Then use it like this

total($(".price"), function(elem) {
  return $(elem).text();
});

I think this approach is nicer because it gives you flexibility over the type of elements you could be total-ing.

For example, if you were trying to total <input> elements, you would want this instead

total($("input"), function(elem) {
  return $(elem).val();
});

Even better, make it into a lightweight jQuery plugin like this

(function(window, $) {
  function total(jq, callback) {
    // code from above
  }

  $.fn.total = function(callback) {
    return total(this, callback);
  };
})(window, jQuery);

Now you can use it like this

$(".price").total(function(elem) {
  return $(elem).text();
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.