Question

I am having some trouble with my verification. Here, an input is being checked that it is a number, is not = to nothing, and it is greater than or = to 3 and less than or = to 12. For some reason, I am only able to successfully verify the first part. I cannot get the ">3= && <=12" to work, plz help.

}else if(question_pos==2){
        if( $("#myinput").val() != "" && Number($("#myinput").val() ) && $("#myinput").val() >= "3" && $("#myinput").val() <= "12" ){
        return true;
    }else{
        return false;
    }

This is the problem part

$("#baseline_05_ft").val() >= "3" && $("#baseline_05_ft").val() <= "12"
Was it helpful?

Solution 3

First with javascript you should be using the === operator when doing logical comparisons. Second your problem part is comparing two strings, not numbers. Try converting them to a number first.

var myInput = parseInt($('#myinput').val(), 10); //always declare a base when doing parseint
if(myInput >= 3 && myInput <= 12){
    //its valid do stuff to it
}

OTHER TIPS

Your code is messy, that is probably what causes the error.

Write it like so:

var value = parseInt($("#myinput").val(), 10 /*radix*/);
if (isNaN(value) === false && value >= 3 && value <= 12) {
    // ..
}

Never compare strings where you mean numbers. Compare what you should be comparing. It makes the code easier to read and understand.


This also allows you to use strict comparison (!== and ===) as:

3 === 3; // true
3 === "3"; // false
3 == "3"; // true

I've never found a case where you want to use == instead of ===.

You should convert it to integers-

var myVal = parseInt($("#myinput").val(), 10);
if(!isNaN(myVal) && myVal >= 3 && myVal <= 12) {
    //do stuff
}

You are comparing strings, not numbers. There is no value that compares lexically greater than "3…" but lower than "1…".

if (question_pos==2) {
    var strVal = $("#myinput").val();
    var val = Number(strVal);
    return strVal != "" && !isNaN(val) && val >= 3 && val <= 12;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top