3

I am trying to add to a variable and get the total price at the end of the loop and add it to a value in a span tag and update it. I am unsure how to do with jquery, I usualy do it with php. This is what I have tried but I get nothing.

$.each(data, function(key, obj) {
    items.push('<li id="' + obj.id + '">' + obj.title + '€' + obj.price + '</li>');
    totalprice += obj.price
});

$("#addonPrice").html($("#addonPrice").text() + totalprice);
2
  • 4
    Did you add "var totalprice = 0;" before the call to each()? And also, is obj.price a string or a number? Commented Oct 14, 2011 at 21:55
  • 1
    Can you show us a sample of the data object? Commented Oct 14, 2011 at 21:56

5 Answers 5

5

Try the following:

var totalprice = 0;

$.each(data, function(key, obj){
    items.push('<li id="' + obj.id + '">' + obj.title + '€' + obj.price + '</li>');
    totalprice = totalprice + parseFloat(obj.price);
});
$('#addonPrice').html(parseFloat($('#addonPrice').text()) + totalprice);

You need to initialize the total price and convert the price / addon price to a float to work with them as numbers.

I hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

4

You should initialize totalprice to zero before the loop as well as apply parseFloat() to obj.price before adding it:

var totalprice = 0;
$.each(data, function(key, obj) {
    items.push('<li id="' + obj.id + '">' + obj.title + '€' + obj.price + '</li>');
    totalprice += parseFloat(obj.price);
});
$("#addonPrice").html(parseFloat($("#addonPrice").text()) + totalprice);

Comments

3

try this :

totalprice += parseInt(obj.price);

Comments

2

There are a couple of things about this. First you haven't shown where and how is the totalprice variable being initialized. Normally this should be done outside of the loop. Secondly depending on the type of obj.price, the += operator you are using might perform string concatenations instead of number additions. Also the .text function returns a string so you need to cast it to a number when performing the addition at the end of the loop:

var totalprice = 0;
$.each(data, function(key, obj) {
    items.push('<li id="' + obj.id + '">' + obj.title + '€' + obj.price + '</li>');
    totalprice += Number(obj.price);
});

$("#addonPrice").html(parseFloat($("#addonPrice").text()) + totalprice);

Comments

1

You need to instantiate totalprice before the loop as the totalprice will cease to exist out of the context of $.each.

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.