简体   繁体   中英

JavaScript doesn't recognize input.min, input.max, input.value as integers

I'm working on a website, and I want the number inputs to correct themselves if the number is not between the min and the max before the form gets submitted. My code is as follows:

HTML:

<input type="number" min="0" max="10" step="0.01" onblur="CorrectOverUnder(this)" value="0">

JavaScript:

function CorrectOverUnder(sender){

    if(sender.value < sender.min){

        sender.value = sender.min;

    }else if(sender.value > sender.max){

        sender.value = sender.max;
    }
}

It works just fine correcting anything that's out of range, but it also corrects anything between 2 and 10 to it's max (which is 10). I've tried reversing the order of the cases by having it check for a number above the max first, but the result is the same. How do I fix this?

EDIT: I ended up changing the JavaScript to this:

function CorrectOverUnder(sender){

    if(parseInt(sender.value) < parseInt(sender.min)){

        sender.value = sender.min;

    }else if(parseInt(sender.value) > parseInt(sender.max)){

        sender.value = sender.max;
    }
}

All good, or is this still wrong in some way?

You need to convert the values to numbers before comparing them, because when they are strings JS compares them alphabetically and that means "2" > "10"

 function CorrectOverUnder(sender) { let value = Number(sender.value); let min = Number(sender.min); let max = Number(sender.max); if(value < min){ sender.value = min; }else if(value > max){ sender.value = sender.max; } } 
 <input type="number" min="0" max="10" step="0.01" onblur="CorrectOverUnder(this)" value="0"> 

Change to this:

var parsedValue = +sender.value;
var parsedMin = +sender.min;
var parsedMax = +sender.max;

if(parsedValue  < parsedMin){

    sender.value = parsedMin;

}else if(parsedValue > parsedMax){

    sender.value = parsedMax;
}

The commenter who said you are matching strings and not numbers is correct, so you have to cast to numbers first. "2" is > "10" alphabetically, which is why the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM