John Funk
John Funk

Reputation: 98

jQuery Fetching data and making sum

What i'm trying to do is taking the price of every input checked, making a sum out of it.

Here's my code

    function totalSum(e) {
    e.preventDefault();
    var unit = $("input:checked").parent("dt").siblings("dd").find("span"); 
    total = 0;
    $.each(unit, function(index, obj){
        total += parseInt($(obj).text(), 10);
    });
    $("#totalPrice").html('<span class="count">€ ' + total + '</span> €');
}

Every unit is found inside its span. Total is set to 0. I try to call a parseInt on each checked object, then add the total inside a span. In HTML, price is stated like that:

    <dd><span class="costo">€199</span></dd>

So as you see there is the Euro mark. I am afraid it could not be parsed, is this it? Because nothing change! How should I write it? Thanks in advance

Ok I feel so ashamed but I cannot get it to work. I decided to put the code at its minimum, so I tried that way

    <body>
    <div class="bla"><span class="count">1</span></div>
    <div class="bla"><span class="count">1</span></div>
    <div class="bla"><span class="count">1</span></div>

    <div id="total"></div>
    <script type="text/javascript" src="js/jquery-1.9.0.min.js" /></script> 
    <script>
    $(document).ready(function(){


    function sum() {
        var prices = $("div.bla").find(".count");
        total= 0;
        $.each(prices, function(index, obj){
    total += parseFloat($(obj).text());
});

$("#total").html('<span class="count">'+total +'</span> €');
    };

});

This should work, yet nothing appear. Could someone be so kind to tell me what's going wrong?!

Upvotes: 0

Views: 214

Answers (4)

John Funk
John Funk

Reputation: 98

After a couple of days trying and reading the best way to do it, I believe this could be an elegant solution of what I was trying to achieve :)

$("input").on("click", function() {
    var j = $("input:checked");
    t = 0;
    $(j).each(function() {

        t += parseInt(this.value, 10);
    });
    $("#total").html("<span>€ " + t + "</span>");
    });

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

You can simply remove the unit from the text :

var text = $(obj).text().replace(/[€\$]/,''); // add other units if needed
total += parseInt(text, 10); // are you sure you don't prefer parseFloat ?

Or, if you want to only keep digits and + and -, do

var text = $(obj).text().replace(/[^\d\-\+]/g, '');

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

You can just replace any non-numeric characters:

total += parseInt($(obj).text().replace(/[^\d.-]/, ''), 10);

Also, you can do unit.each() instead of $.each(unit, but that has no effect on what you're trying to do.

Upvotes: 1

Manuel Quinones
Manuel Quinones

Reputation: 4246

Change your parseInt to skip the first character.

total += parseInt($(obj).text().substring(1),10);

Upvotes: 0

Related Questions