Leo T Abraham
Leo T Abraham

Reputation: 2437

Get the total count using Jquery in ul

Following is my structure of ul li

<ul>
<li> <a href="#">Top Level </a>

    <ul>
        <li> <a href="#">Level 1_1</a>

            <ul>
                <li> <a title="" class="grower OPEN">Level 2_1</a>

                    <ul>
                        <li> <a title="" href="#">Level 3_1 </a><span>(1)</span>
                        </li>
                        <li> <a title="" href="#">Level 3_2 </a><span>(4)</span>
                        </li>
                    </ul>
                </li>
                <li>    <a href="#">Level 2_2 </a>

                    <ul>
                        <li>    <a href="#">Level 3_1 </a><span>(5)</span>
                        </li>
                        <li>    <a href="#">Level 3_2 </a><span>(1)</span>
                        </li>
                    </ul>
                </li>
            </ul>
        </li>
        <li> <a href="#">Level 1_2 </a>

            <ul>
                <li>    <a title="" href="#">Level 2_1 </a><span>(3)</span>
                </li>
            </ul>
        </li>
        <li>    <a title="" href="#">Level 1_3 </a><span>(2)</span>
        </li>
        <li>    <a title="" href="#">Level 1_4 </a><span>(1)</span>
        </li>
    </ul>
</li>

I have count of products shown along with the lower level of category. What I want is, show the total count against parent of each category using jquery. I have no idea on how to do this.

Current System: http://jsfiddle.net/jvfwhs3f/1/

Required Output: http://jsfiddle.net/fz554136/

Upvotes: 0

Views: 179

Answers (1)

Chin Leung
Chin Leung

Reputation: 14921

Here's a JSFiddle of what I did.

Basically I added a class to all your spans with the count and looped through each li to add the total of each span within the li. But I'd recommend using a data attribute in your spans (<span count="5">(5)</span>) with the total count so you can parse the number directly with parseInt($(this).data('count'))

$(document).ready(function(){    
    $('ul li').each(function(){
        var $this = $(this);
        var totalSpan = $this.find('span.green');
        var total = 0;
        $this.find('span.total').each(function(){
            total += parseInt($(this).text().replace(/[^0-9]+/g, '')); 
        });
        totalSpan.html("(" + total + ")"); 
    });
}); 

Upvotes: 1

Related Questions