0

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 
3
  • What exactly is happening when you are saying this does't work? Commented Feb 26, 2018 at 6:54
  • Can you add a working code snippet demonstrating the problem? Commented Feb 26, 2018 at 6:57
  • i'm using a Backend with ajax so i theres lot of code. Whats happening is that when i use this tot *= Number($(this).val()) || 0 i get the output as 0 so the multiplication doesn't work. I'm supposed to get the value of the 2 inputs multiplicative output . i.e, 500 * 2 = 1000 .Thanks :D Commented Feb 26, 2018 at 7:06

2 Answers 2

3

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'); 
Sign up to request clarification or add additional context in comments.

1 Comment

ohh...that's great...!
2

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.

2 Comments

Omg!! Thank you so much mate it works :D cheers @void your a life saver.
cheers Void :D ha! you made my day. Glad to be a dev. What a great Industry were in.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.