Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

javascript - Limit number input to range

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

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

1 Reply

0 votes
by (71.8m points)

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...