I want to limit a user input to a specific range (-90 to 90). Number can be integer or decimal. The default value must be 0
. I do not want to use HTML5 min
/ max
attributes.
This is my HTML:
<input type="number" value="0" />
This is what I have tried:
$('input').on('input', function () {
var value = $(this).val();
$(this).val(Math.max(Math.min(value, 90), -90));
});
This is buggy because it doesn't let me erase the default value (therefore I cannot enter a -
for a negative number or a .
for a decimal number).
So I ended up doing this:
$('input').on('input', function () {
var value = $(this).val();
if ((value !== '') && (value.indexOf('.') === -1)) {
$(this).val(Math.max(Math.min(value, 90), -90));
}
});
That's better, but now the problem is that I can enter 90.1
which is out of my defined range.
Suggestions?
JSFiddle demo
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…