Reputation: 67
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?
Upvotes: 0
Views: 83
Reputation: 3879
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">
Upvotes: 2
Reputation: 4845
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.
Upvotes: 1