Kimson Dooland
Kimson Dooland

Reputation: 55

Jquery Multiplication not working? But addition works

I'm trying to multiply 2 values from input box and store it in the last row of that column. The adding works perfectly for this but the multiplication does not work.

I want to multiply all the row inputs. I got an example for addition why doesn't multiplication work ?

I've tried
tot *= Number($(this).val()) || 0 //this does't work.
tot = ((tot) * (Number($(this).val()) || 0)) //this doesn't work.

$('table input').on('input', function() {
    var $tr = $(this).closest('tr'); // get tr which contains the input
    var tot = 0; // variable to sore sum
    $('input', $tr).each(function() { // iterate over inputs
        tot += Number($(this).val()) || 0 // i want to multiply here. The addition works perfectly     
    });
    $('td:last', $tr).text(tot); // update last column value
}).trigger('input'); // trigger input to set initial value in columns

Upvotes: 0

Views: 364

Answers (2)

Hari17
Hari17

Reputation: 489

You can also try this code snippet. Here I assigned tot = 1, because multiplication with zero will provide a result of zero. So initialisation must not be zero, and I modified the multiplication statement to

"tot *= Number($(this).val())"

Final code will be:

$('table input').on('input', function() {
        var $tr = $(this).closest('tr'); 
        var tot = 1; //variable to store product
        $('input', $tr).each(function() { 
            tot *= Number($(this).val())      
    });
    $('td:last', $tr).text(tot); 
}).trigger('input'); 

Upvotes: 3

void
void

Reputation: 36703

In case of addition you are trying to add a 0 when there is no value. So it wont affect anything in the addition.

But if you will try to multiply the whole value will 0 if some input does not have value then the whole value will become a zero, and will remiain zero forever. Anything * 0 = 0.

So instead do:

tot *= Number($(this).val()) || 1 

Also in case of multiplication initialize tot with a value of 1 and not 0.

Upvotes: 2

Related Questions