jennifer Jolie
jennifer Jolie

Reputation: 727

Total number with jquery

How can total the number of characters between the p tags with jQuery?

I try as:

DEMO

html:

<b>1</b>
<b>1</b>
<b>1</b>

js:

var tBytes = 0,
    tFiles = $('b').length;
for (var tFileId = 0; tFileId < tFiles; tFileId++) {
    tBytes += $('b').text();
}
alert(tBytes);​ // Output is : 0111111111 I want output as: 3

What do i do?

Upvotes: 0

Views: 227

Answers (5)

A. Wolff
A. Wolff

Reputation: 74420

You could do it in pure javascript quite easily too, no need of jquery:

var tBytes  = 0,
    tFiles= document.getElementsByTagName('b');

for(var i=0,z=tFiles.length;i<z;i++) { 
    tBytes += +(tFiles[i].textContent || tFiles[i].innerText);
}

alert(tBytes);​

Upvotes: 0

Rikki
Rikki

Reputation: 3518

You can also take a look at this code:

Array.prototype.Sum = function()
{
    var result = 0;

    $(this).each(
        function()
        {
             result += this;
        }
    );

    return result;
};

alert($("b").map(function () { return parseInt($(this).text()); }).toArray().Sum());

JSFiddle here

Or even this one if you are interested:

$.fn.Sum = function()
{
    var result = 0;

    $(this).each(
        function()
        {
             result += this;
        }
    );

    return result;
};

alert($("b").map(function () { return parseInt($(this).text()); }).Sum());

JSFiddle here

And finally my favourite here:

$.fn.Sum = function(action)
{
    var result = 0;

    $(this).each(
        function()
        {
             result += action.call(this);
        }
    );

    return result;
};

alert($("b").Sum(function () { return parseInt($(this).text()); }));

JSFiddle here

Upvotes: 0

j08691
j08691

Reputation: 207861

var tBytes = 0,
    tFiles = $('b').length;
$('b').each(function(){
    tBytes += parseInt($(this).text(),10);
});
console.log(tBytes);

jsFiddle example

Upvotes: 1

Atif
Atif

Reputation: 10880

var total = 0
$('b').each(function(index, element) {
    total += $(element).text().length;
})
alert(total);​

http://jsfiddle.net/TPFkF/2/

Upvotes: 2

Meliborn
Meliborn

Reputation: 6645

$('b').each(function(){
total += parseInt($(this).text());
})

Upvotes: 1

Related Questions