Show error alert if value is outside range on button press

I have a ‘calculate’ button that takes the quantity entered and multiplies it by the value of an item. JS is below:

function calculate() {

   var totalPrice=0;
   var price = document.getElementById("itemprice").innerHTML;
   var quantity = document.getElementById("quantity").value;

   totalPrice=price * quantity;
   document.getElementById("totalamount").innerHTML="$" + totalPrice;
   //document.write(price * quantity)
}
   

The above works perfectly for the calculate button. I’m looking to add to this

What I want to also achieve is adding an alert pop up should the “totalprice” result equals zero, a negative number, or NaN (if someone inputs a letter into the quantity box).

So adding to the above something like this:

if ("totalPrice" < 1, NaN)

   alert (Please Enter valid quantity)

But I just don’t seem to be able to make it work.

Answer

  1. totalPrice is variable, if you put it in quotes its a string
  2. if you need 2 conditions in if use || an or operator in your case. Also read: javascript multiple OR conditions in IF statement
  3. Read here how to check for NaN
    totalPrice = "not a number"
    
    if (isNaN(totalPrice) || totalPrice < 1) {
      alert("Please Enter valid quantity")
    }

So you should use:

   function calculate() {

  var totalPrice = 0;
  var price = document.getElementById("itemprice").innerHTML;
  var quantity = document.getElementById("quantity").value;

  totalPrice = price * quantity;

  if (isNaN(totalPrice) || totalPrice < 1) {
    alert("Please Enter valid quantity")
  } else {
    document.getElementById("totalamount").innerHTML = "$" + totalPrice;

  }
}