KayKay
KayKay

Reputation: 401

Sum operation on Textbox

I have multiple textboxes (with class txtsum) which should allow only numbers. How can I calculate the sum of all these textboxes as the user types in the textbox

var $txtb = $(':input.txtsum');
$txtb.on('change',function(){
    tot = 0.0;
    $txtb.each(function() {
        tot += parseFloat($(this).text());
    });
});

Can you suggest me the right/better way to do it? Here's what I tried http://jsfiddle.net/DPe4W/

Upvotes: 0

Views: 714

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

.text() does not work with input types.. Use .val() instead

Instead of

 $(this).text()

use

($(this).val() ; // To calculate the value

FULL CODE

    var $txtb = $(':input.txtsum');
$txtb.on('keyup', function() {
    tot = 0.0;
    $txtb.each(function() {
        var t = $(this).val() != '' ? $(this).val() : 0;
        tot += parseFloat(t);
    });
    $("p").html(tot);
});​

Check Fiddle

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79840

Change

tot += parseFloat($(this).text());

to

tot += parseFloat($(this).val()); 

You should use .val to get the value of any input elements like input, select.

Also I changed your code like below,

DEMO: http://jsfiddle.net/DPe4W/7/

var $txtb = $(':input.txtsum');
$txtb.on('keyup', function() {
    var tot = 0.0;
    $txtb.each(function() {
        var val = parseFloat(this.value);
        if (!isNaN(val)) {   
           tot += val;
        }
    });

    $("p").html(tot);
});

Upvotes: 4

Related Questions