Javascript number comparison fails

formsjavascript

I'm trying to understand where is my error, because it's not possible that JS fails in math!

On the HTML form I have a select and 9 text input.
Then, on the JS I compare the text entered.

My problem is the following:
If I write on

new_da3 = 1400
new_a3 = 1900

the JS will say ok3.

If I write on

new_da3 = 1900
new_a3 = 1400

the JS will say no3!

BUT If I write on

new_da3 = 1500
new_a3 = 800

the JS WILLL SAY ok3!

Why? Isn't 1500 bigger than 800?

Thank you!

HTML:

 <form>
 <select id="new_nrp" onchange="selNrP(this.value);" style="background-color:#F00; color:#FFF">
            <option value="" selected="selected"></option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>

    <?php
    for($i=1; $i<=3; $i++){
        print '<input type="text" size="5" maxlength="5" id="new_da'.$i.'">
               <input type="text" size="5" maxlength="5" id="new_a'.$i.'">';

    }
    ?>

    <input type="submit" class="buttongreen" onClick="test()" value="Try the test function!">
</form>

JS

function test(){
    var new_da1 = document.getElementById('new_da1').value
var new_a1 = document.getElementById('new_a1').value
var new_da2 = document.getElementById('new_da2').value
var new_a2 = document.getElementById('new_a2').value
var new_da3 = document.getElementById('new_da3').value
var new_a3 = document.getElementById('new_a3').value

var new_nrp = document.getElementById('new_nrp').value

switch(new_nrp){
    case '3':
        if(new_a2 < new_da3 && new_da3 <= new_a3){
            alert('ok3')
        } else {
            alert('no3')
            return
        }
    case '2':
        if(new_a1 < new_da2 && new_da2 <= new_a2){
            alert('ok2')
        } else {
            alert('no2')
            return
        }
    case '1':
        if(new_da1 <= new_a1){
            alert('ok1')
        } else {
            alert('no1')
            return
        }
    break;
    default:
        alert("Why are you here?");
        return;
}

}

Best Answer

Because you're comparing strings, not integers. Use parseInt to explicitly cast your values as integers.

Here's essentially what you're doing: jsFiddle example

To do the conversion, change your variables to something like:

var new_da1 = parseInt( document.getElementById('new_da1').value, 10);

(assuming they're all integers)