Yusaf Khaliq
Yusaf Khaliq

Reputation: 3393

adding value for .each

the HTML below

<div class="commentlinks">
    <a class="commentlinked blogcount">3</a>
    <a class="commentlinked fbcount">2</a>
    <a class="commentlinked disqcount">1</a>
    <a class="allcommentcount"></a>
</div>

with this jQuery

$('.commentlinks').each(function() {
var currentValue = parseInt($(".blogcount").text());
var currentValue2 = parseInt($(".fbcount").text());
var currentValue3 = parseInt($(".disqcount").text());
var newValue = currentValue + currentValue2 + currentValue3;
$(".allcommentcount").text(newValue);
});

Returns this successfully http://jsfiddle.net/hQzZQ/22/

3 2 1 6

but when i have this html

<div class="commentlinks">
    <a class="commentlinked blogcount">3</a>
    <a class="commentlinked fbcount">2</a>
    <a class="commentlinked disqcount">1</a>
    <a class="allcommentcount"></a>
</div>

<div class="commentlinks">
    <a class="commentlinked blogcount">7</a>
    <a class="commentlinked fbcount">6</a>
    <a class="commentlinked disqcount">1</a>
    <a class="allcommentcount"></a>
</div>

It Returns http://jsfiddle.net/hQzZQ/23/

3 2 1 74 7 6 1 74

why is it returning it incorrectly help me fix it please!

Upvotes: 0

Views: 64

Answers (2)

Rob W
Rob W

Reputation: 349012

You have to use find or children to select the elements in the current context. Also, use parseInt(.., 10) to parse numbers.

Demo: http://jsfiddle.net/sym7H/

$('.commentlinks').each(function() {
    var $this = $(this);
    var currentValue = parseInt($this.find(".blogcount").text(), 10);
    var currentValue2 = parseInt($this.find(".fbcount").text(), 10);
    var currentValue3 = parseInt($this.find(".disqcount").text(), 10);
    var newValue = currentValue + currentValue2 + currentValue3;
    $this.find(".allcommentcount").text(newValue);
});


If your document is well-structured, you can also use .children("a") to find the elements, then use .eq(..) or .slice(.., 1) to select the elements. This has an improved efficiency.

Demo: http://jsfiddle.net/sym7H/1/

$('.commentlinks').each(function() {
    var $anchors = $(this).children("a"),
        currentValue = parseInt($anchors.eq(0).text(), 10),
        currentValue2 = parseInt($anchors.eq(1).text(), 10),
        currentValue3 = parseInt($anchors.eq(2).text(), 10),
        newValue = currentValue + currentValue2 + currentValue3;
    $anchors.eq(3).text(newValue);
});

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148524

http://jsfiddle.net/hQzZQ/24/

$('.commentlinks').each(function() {
var currentValue = parseInt($(".blogcount",this).text());
var currentValue2 = parseInt($(".fbcount",this).text());
var currentValue3 = parseInt($(".disqcount",this).text());
var newValue = currentValue + currentValue2 + currentValue3;
$(".allcommentcount",this).text(newValue);
});

Upvotes: 0

Related Questions