Search code examples
javascriptmootools

Add two values together in Mootools


My Javascript / Mootools knowledge is limited, so I am having trouble figuring out how to take the following code and make it produce a sum and assign the value to the ordertotal variable.

$('ordertotal').value = '$' + 100 * $('tickets').value + 10 * $('fiftytickets').value + '.00';

The tickets variable is either 1 or 2 depending on the user selection and the fiftytickets variable is either 0.5, 2.5 or 5.0 depending of the user selection. Both variables are supplied values using a HTML select menu and they function correctly when used individually.

For example:

$('ordertotal').value = '$' + 100 * $('tickets').value + '.00';

Works correctly and

$('ordertotal').value = '$' + 10 * $('fiftytickets').value + '.00';

Works correctly, but I can figure out how to add them together and assign them to the ordertotal variable.

Any assistance with this issue would be greatly appreciated.

Thank you.

Mike


Solution

  • Seems like you are trying to get sum of string + int + int + string

    Your two examples worked, because there was only concatenation (string + int(converted to string) + string)

    And when you add a nubmer to a "$" - your number get converted to a string. What you can do is to either put numbers sum in () or get the value separately:

    sumValue = 100 * $('tickets').value + 10 * $('fiftytickets').value
    $('ordertotal').value = '$' + sumValue + '.00';
    

    Example:

    > "1" + 1
      "11"
    > "$" + 1 + ".00"
      "$1.00"
    > "$" + 1 + 1 + ".00"
      "$11.00"
    > "$" + (1 + 1) + ".00"
      "$2.00"