Pringles
Pringles

Reputation: 4615

Jquery sum of attr values for multiple elements

I have a code like this:

<a id="3" class="off area" name = "2" href="">Colchester</a>
<a id="1" class="off area" name = "1" href="">Leicester</a>
<a id="2" class="off area" name = "2" href="">London</a>
<a id="4" class="on area" name = "1" href="">Winchester</a>

And I need the sum of the NAME attribute, for links that have a class "on". (i.e. only Winchester).

$('.area .on').each(function() {
    alert(this.id);
    total += parseInt(this.id, 10);
});

I can count the ID's, but not the NAME attributes. So

total += parseInt(this.id, 10);

is working, but this doesn't:

total += parseInt(this.attr('name'), 10);

Upvotes: 0

Views: 3708

Answers (4)

Adil Shaikh
Adil Shaikh

Reputation: 44740

You are trying to call a jQuery method on DOM element (this)

You need this -

total += parseInt(this.name, 10);

Or

total += parseInt($(this).attr('name'), 10);

Demo -----> http://jsfiddle.net/dtt7u/

Upvotes: 2

kcsoft
kcsoft

Reputation: 2947

var sum = 0;
$('.area.on').each(function(index, elem) {
    sum += parseInt($(elem).attr('name'));
});

.area.on no space

Upvotes: 1

palaѕн
palaѕн

Reputation: 73926

Try this:

total += parseInt(this.name, 10);

Reason being attr is used on the jQuery object, not directly to this keyword.

You can make it better by doing this:

total += parseInt(this.name, 10) || 0;

making sure you always get a numeric value as a sum.

Upvotes: 3

moonwave99
moonwave99

Reputation: 22812

Either you do:

total += parseInt(this.name, 10);

or:

total += parseInt($(this).attr('name'), 10);

BTW, use console.log() over alert().

Upvotes: 1

Related Questions