Europeuser
Europeuser

Reputation: 942

Jquery to sum values of all elements with specific attr value

I have this short menu:

<ul>
    <li class="voucher">
        Holidays (<span data="0" class="counter" id="119">0</span>)
        <ul id="menu2">
            <li class="voucher">
                Travel deals (<span data="119" class="counter" id="123">1</span>)
            </li>
            <li class="voucher">
                Hotel offers (<span data="119" class="counter" id="120">2</span>)
            </li>
            <li class="voucher">
                Villas offers(<span data="119" class="counter" id="121">1</span>)
            </li>
        </ul>
    </li>
</ul>

and this js which has to collect all subcategories values in () and add that sum as (value ) for the main category Holidays:

var sum = 0;
$('.counter').each(function () {
    var counter = $(this).html();
    var id = $(this).attr('id');
    if (counter == 0) {
        // here I want to find and sum all values in ( ) for span that has attr data equal to 119 which is the id of the main category Holidays
        sum += parseInt($('span').find("[data='" + id + "']").html(), 10) || 0;
        alert(sum);
        //here I want the sum of all subcategories -Holidays ( 4 )
        $(this).html(sum);
    }
});

but it doesn't work.. No errors, just doesnt sum correct and returns always 0 Please help with this if you are OK with JS,

Here is jsfiddle: http://jsfiddle.net/europe77/w1uL5a8o/1/

Upvotes: 4

Views: 2996

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You are trying to find by data attribute in span object.You need to use:

parseInt($("span[data='" + id + "']").html());

Also there were other issue that needs to be addressed. Here is the full working code:

var sum = 0;
$('.counter').each(function () {
  var counter = $(this).html();
  var id = $(this).attr('id');
  sum += parseInt($(this).html(), 10) || 0;
});
alert(sum);
$('.counter:eq(0)').html(sum);

Working Demo

Upvotes: 4

Related Questions