Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
327 views
Welcome To Ask or Share your Answers For Others

1 Answer

Consider only modifying the value when it's out of range. This lets you include decimals, etc.

$('input').on('input', function () {
    
    var value = this.value;
    
    if (value !== '') {
        value = parseFloat(value);
        
        if (value < -90)
            this.value = -90;
        else if (value > 90)
            this.value = 90;
    }
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="number" value="0" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...