Search code examples
jqueryjquery-selectors

If/else else if in Jquery for a condition


I am having a set of text fields where i am doing validation Say I am Having a field called "seats" this can accept value less than "99999".Meaning I should not able to enter the "99999" any thing less than that is ok. For that I wrote below if and else if . please tell me whether I am doing any thing wrong. I am confused a lot from morning whether it should be less than or greater than

if ($("#seats").val() != '') {
    setflag = false;
    alert("Not a valid character")
}
else if($("#seats").val() < 99999) {
    alert("Not a valid Number");
} else {
    setflag = true;
}

Solution

  • Iam confused a lot from morning whether it should be less than or greater than`

    this can accept value less than "99999"

    I think you answered it yourself... But it's valid when it's less than. Thus the following is incorrect:

    }elseif($("#seats").val() < 99999){
      alert("Not a valid Number");
    }else{
    

    You are saying if it's less than 99999, then it's not valid. You want to do the opposite:

    }elseif($("#seats").val() >= 99999){
      alert("Not a valid Number");
    }else{
    

    Also, since you have $("#seats") twice, jQuery has to search the DOM twice. You should really be storing the value, or at least the DOM element in a variable. And some more of your code doesn't make much sense, so I'm going to make some assumptions and put it all together:

    var seats = $("#seats").val();
    
    var error = null;
    
    if (seats == "") {
        error = "Number is required";
    } else {
        var seatsNum = parseInt(seats);
        
        if (isNaN(seatsNum)) {
            error = "Not a valid number";
        } else if (seatsNum >= 99999) {
            error = "Number must be less than 99999";
        }
    }
    
    if (error != null) {
        alert(error);
    } else {
        alert("Valid number");
    }
    
    // If you really need setflag:
    var setflag = error != null;
    

    Here's a working sample: http://jsfiddle.net/LUY8q/