0

My javascript is behaving very strange!

I have a input field in my html file. This input field is read by javascript in the following way:

var bscore = $("#bscore").val();

Then i want to show an alert if the input is below a certain input

if(bscore<"913"){
    document.getElementById("bscorealert").style.display="block";
};

This works fine. So when the number is above 913 it should not show. Only javascript is behaving very strange, when the number in the bscore input field is above 999 (so 1000 and higher) the if statement is triggered and the alert is shown.

How is this possible?

j08691
  • 204,283
  • 31
  • 260
  • 272
NBISDB
  • 9
  • 2

2 Answers2

5

It's possible because you are comparing strings, not integers. String comparison is lexicographical, so "9" > "10" and so on.

You will want to convert before comparing with Number(strValue) or with the unary operator +:

var bscore = +$("#bscore").val();    // + prefix converts to number
if (bscore < 913) ...                // no quotes around 913!
Jon
  • 428,835
  • 81
  • 738
  • 806
  • +1 for the "prefix converter" stuff. Didn't knew that – Claudio Holanda Oct 23 '13 at 13:26
  • @Kazzkiq: That's precisely why you might want to use `Number(whatever)` instead -- it's way more self-explanatory. ;-) – Jon Oct 23 '13 at 13:27
  • I didn't need to convert the input to a number, but the removal of the quotes did the trick! Thanks a lot! – NBISDB Oct 23 '13 at 13:30
  • Two notes: When converting user input (as from an input field), it's best to use `parseInt` and specify the radix, e.g. `var bscore = parseInt($("#bscore").val(), 10);`. 2. If you don't feel like doing that, and you use a number for one of the operands, the first thing the JavaScript engine will try to do is convert the other operand to a number. So `if ($("#bscore").val() < 913)` will compare numerically. – T.J. Crowder Oct 23 '13 at 13:30
  • @NiekBakermans: That's because when comparing a string to a number, the engine will auto-convert the string to a number. Still best to use `parseInt` on end-user input, though. – T.J. Crowder Oct 23 '13 at 13:31
  • @T.J.Crowder I added this to my code, don't need it on my own machine (safari), but the finished product will be used on IE8. So better be safe than sorry with that browser. – NBISDB Oct 23 '13 at 13:33
  • @T.J.Crowder: I consciously decided against `parseInt` because that would "validate" input such as "10asdfasdf". Converting both operands explicitly is indeed not required, but I prefer it because the code reads closer to what it does. – Jon Oct 23 '13 at 13:36
  • @Jon: Ah, yes, you do need to handle that (surprising) behavior of `parseInt`. – T.J. Crowder Oct 23 '13 at 13:39
1

You're trying to compare 2 strings, which uses the alphabetical comparison. If you enter a value between 9130 and 9999 in the field, you'll notice that the messagebox doesn't show as well.

You'll have to do a parseInt to compare numerical values.

Nzall
  • 3,439
  • 5
  • 29
  • 59