0

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?

wessltov
  • 67
  • 6
  • 3
    the max and min properties (and attributes) contain strings. If you want to compare them to numbers, you'll have to convert them to numbers. Why do you need to do this in the first place? – Kevin B Jan 02 '18 at 18:35
  • 1
    GIven you've specified `min` and `max`, you wouldn't need to correct that your own self. – OverCoder Jan 02 '18 at 18:35
  • Fair enough, the form wouldn't submit if the values are invalid. Still, I just thought I'd add this in case someone accidentally went over 10. – wessltov Jan 02 '18 at 18:38

2 Answers2

2

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">
mdatsev
  • 3,054
  • 13
  • 28
1

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.

codeMonkey
  • 4,134
  • 2
  • 31
  • 50