Limit number input to range

冷暖自知 提交于 2019-12-13 10:18:16

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/26653705/limit-number-input-to-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!