notaceo
notaceo

Reputation: 1093

JavaScript IF statement evaluating TRUE incorrectly - why?

I have a very, very simple logical test of the number of licenses a customer has purchased vs. the number they have used:

else if(utype == "3"){
           var tech_lic = $("#technician_lic").val();
           console.log('tech lic = ' + tech_lic)
           var tech_allow = $("#technician_lic_allow").val();
           console.log('tech allow = ' + tech_allow)
           if(tech_lic >= tech_allow)
            {
              alert("You must purchase more licenses to create this Technician");
              return false;
            }

I threw in the console.log statements trying to debug this - normally they aren't there.

Console.log when I click "add" button:

tech lic = 4    application.js:262
tech allow = 100    application.js:264

Then we hit "You must purchase more licenses" alert in the window.

WHAT THE HECK?

How can 4 >= 100 evaluate true?

Upvotes: 0

Views: 189

Answers (5)

Guffa
Guffa

Reputation: 700342

It's not that 4 >= 100 is true, it's that "4" >= "100" is true.

The values that you get are strings, so they will be compared lexically, not numerically.

Parse the values into numbers:

var tech_lic = parseInt($("#technician_lic").val(), 10);
var tech_allow = parseInt($("#technician_lic_allow").val(), 10);

Upvotes: 1

Ken Herbert
Ken Herbert

Reputation: 5236

You are evaluating them as strings, so "4" IS greater than "100".

You will need to cast them as integers before comparison:

var tech_lic = parseInt($("#technician_lic").val(), 10);
var tech_allow = parseInt($("#technician_lic_allow").val(), 10);

Upvotes: 3

Siva Charan
Siva Charan

Reputation: 18064

Do this way:-

if(Number(tech_lic) >= Number(tech_allow))
{
   // Do your stuff
}

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

Because .val returns a string. '4' is indeed greater than or equal to '100'. Cast the values to numbers first (if you know that they are always numbers for the purposes of this comparison).

if (+tech_lic >= +tech_allow)

Upvotes: 7

xagyg
xagyg

Reputation: 9711

The string "4" is greater than "100", whereas the number 4 is less than 100.

Upvotes: 1

Related Questions