Javascript number comparison fails

I'm trying to figure out where my mistake is, because it is not possible for JS to fail in math!

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

My problem is this: If I write to

new_da3 = 1400
new_a3 = 1900

JS will say ok3.

If I write in

new_da3 = 1900
new_a3 = 1400

JS will say no3!

BUT if I write to

new_da3 = 1500
new_a3 = 800

JS WILLL SAY ok3!

Why? Is not 1500 more than 800?

Thank!

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

}
+5
source share
2 answers

Because you are comparing strings, not integers. Use parseIntto explicitly indicate your values ​​as integers.

What you do is essential here: jsFiddle example

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

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

(if they are all intact)

+7

user parseInt parseFloat float

parseInt Help parseFloat Help

+4

All Articles