0

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.

Minal Chauhan
  • 6,025
  • 8
  • 21
  • 41

1 Answers1

0
  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;

  }
}
ikiK
  • 6,328
  • 4
  • 20
  • 40
  • Thank you! worked perfectly. Still learning so getting the text into the right order is where I am having the most trouble at the moment. Seeing the final work showed me exactly what was needed. Thank you. – wastedhate Apr 05 '21 at 00:25