max value 50% of other values

37 Views Asked by At

I'm very new to javascript, I'm trying to input a maximum value of 50% of the selling price, please advise

I have two fields "sale_price" and "discount"

enter image description here

How does JavaScript limit and change the discount nominal input so that it does not exceed 50% of the selling price

1

There are 1 best solutions below

0
Christopher Owen On BEST ANSWER

You could use an if / else statement here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else

Basically say

if(sale_price < (normal_price * 0.5)) {
   var something = (normal_price * 0.5)
  } else {var something = sale_price}

Or the better route which I prefer ternary linked below https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator

sale_price < (normal_price * 0.5)?
sale_price = (normal_price * 0.5):
sale_price

You'd want to chose the approach based on the type of variable that the sale_price is. If it's a const you'll need to create a different variable and I'd use an if / else statement. If it's changeable you'd do better to use an ternary.

Hope this helps!