Search code examples
jquerysumcalculationmultiplication

Sum and Multiply output is wrong


I have 4 fields that needs to be summed up which I do with sum up with $('select :selected').each(function() { But somehow the below code outputs 99 while it needs to output 72.

// Count for ShowerCoins
$(document).ready(function() {
$('select.countForShowerCoins').on('change', function() {
  var sum = 0;

   $('select :selected').each(function() {
       sum += Number($(this).val() * 3) * $('select[name=howManyNights]').val();
   });

$(".result").html(sum);
  });

});

The sum is "4 input fields with a value of the number 2 each" which is 8 summed up. Then multiplied by 3 and that is 24, then I multiply it with the amount of night's which is 3. 24 * 3 = 72. But somehow I get a output of 99.

Does someone know how this can be, am I missing something? I used parseInt( on the $('select[name=howManyNights]').val(); but that didn't change anything. I noticed that it is because of the sum because when I replace that with a static number the calculation works.

But I don't know how to fix it.


Solution

  • I think you may have an order of operation issue. According to your description you want to sum the inputs THEN x 3 x nights. Also $('select[name=howManyNights]') is a select, so it would be included in $(select :selected).each() which may be why you're getting an unexpected output.

    I'm taking some liberties in guessing what the rest of your code looks like, but hopefully this helps:

    $('select.countForShowerCoins').on('change', function() {
      let sum = 0
    
      $('select.countForShowerCoins').each(function() { sum += Number(this.value); })
    
      $(".result").html(sum * 3 * Number($('select[name="howManyNights"]').val()));
    });
    

    https://jsfiddle.net/t2jdsk0q/1/ This has the expected output with your given inputs.

    Side note: Number($(this).val() * 3) should be Number($(this).val()) * 3.

    Fortunately javascript coerces strings to numbers for division/multiplication/subraction, but not for addition.

    i.e. 2 * '3' = 6 but 2 + '3' = '23'