Shaun
Shaun

Reputation: 559

javascript bigger than if statement not working correctly

I am no expert in javascript, so hope someone can help me out.

I have the following code, but for some reason it always thinks the statement is true

delvNum=document.getElementById("deliveryNum").value;
delvQTY=document.getElementById("delvQTY"+id).value;
orderQTY=document.getElementById("orderQTY"+id).value;

if (delvQTY>orderQTY)
{
  alert("Can't deliver more than " + orderQTY + ", you are trying to deliver " + delvQTY + ". Please fix!");
  document.getElementById("delvQTY"+id).focus();
  return;
}

The error message does show the quantity of each var, and is correctly being passed through.

Upvotes: 1

Views: 426

Answers (4)

RichieHindle
RichieHindle

Reputation: 281425

You're comparing the string values, rather than numerical ones. You should say:

delvNum = parseInt(document.getElementById("deliveryNum").value, 10);

(assume you are dealing with integers, else use parseFloat).

Note the 10 to say you're dealing with base 10 - without it, if someone types a leading zero then you'll get baffling results.

Upvotes: 1

Amy
Amy

Reputation: 7466

You need to make sure delvQTY and orderQTY are Number before you can do > comparison.

var delvValue = parseInt(delvQTY, 10); for converting to integers.

Or for floating point numbers: var delvValue = parseFloat(delvQTY);

Upvotes: 1

epascarello
epascarello

Reputation: 207501

You are comparing strings and not numbers.

Use parseInt or parseFloat

if (parseFloat(delvQTY)>parseFloat(orderQTY))

or

if (parseInt(delvQTY,10)>parseInt(orderQTY,10))

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382122

You're doing a string comparison, not number comparison and, for example, "9">"1111" is true.

You need to parse your values :

if (parseFloat(delvQTY)>parseFloat(orderQTY)) 

See parseFloat.

Upvotes: 1

Related Questions