0

I have a JavaScript if statement that does the following:

If a payment method called cardless is chosen, then the cardfee varable is set to be 1% of the total fee.

if (document.getElementById('payment_method').value == "Cardless") {
    cardfee = ((thetotal * (1 + vatrate)) * 0.01);    
}    
document.getElementById('card_fee').value = cardfee;    
formatPrice(document.getElementById('card_fee'));

The problem is that while the 1% of the total fee is fine, the payment method has a cap. Its 1% but a maximum of £2.

How would I make it do the calculation above, but then add another line that says if cardfee is greater than £2, set cardfee to £2?

Gustavo Gondim
  • 1,635
  • 2
  • 18
  • 39
  • 1
    `if (cardfee > 2) { cardfee = 2; }` ? – David Sep 25 '13 at 17:25
  • 3
    just a little note, and maybe you know this, but if there are actual monetary implications to what the client chooses, you shouldn't be doing it client side. A user could alter that and submit a lower amount for processing. Ensure you have server-side rules in place as well – Jonathan Sep 25 '13 at 17:28

2 Answers2

3

You don't need to change the conditional, you can just change how you assign the new value. Using Math.min() you can assign it to the lesser of two values:

if (document.getElementById('payment_method').value == "Cardless") {
    cardfee = Math.min(((thetotal * (1 + vatrate)) * 0.01), 2.0);
}

That way if the resulting calculation is greater than 2.0, the assignment will be to 2.0. Otherwise, the assignment will be to the calculation result. (If the two are equal, then it doesn't matter which one is used.)

David
  • 208,112
  • 36
  • 198
  • 279
0

Just add the second statment to the inside of your if block

if (document.getElementById('payment_method').value == "Cardless") {
  cardfee = ((thetotal * (1 + vatrate)) * 0.01);
  if (cardfee > 2.0) {
    cardfee = 2.0
  }
}
document.getElementById('card_fee').value = cardfee;
formatPrice(document.getElementById('card_fee'));
Mike Clark
  • 11,769
  • 6
  • 39
  • 43