Limiting number value in an input tag with javascr

2019-09-05 15:33发布

I am creating a form and i want the input tag to accept numbers only and i also want to limit the numbers to be from 0 - 20.

This my html code:

<input type="text" name="three" class="actual" id="three" maxlength="2" onkeypress="return ForNumbers(event)" />

This is my javascript code:

    <script type="text/javascript">
        function ForNumbers(evt){
        var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
return true;
        }
    </script>

3条回答
成全新的幸福
2楼-- · 2019-09-05 15:54

Use html type number and inline elements min="1" and max="20" to limit your input field.

<input type="number" min="1" max="20" />
查看更多
放我归山
3楼-- · 2019-09-05 16:06

If you need to support old browsers, try this:

    function ForNumbers(evt){
        var charCode = (evt.which) ? evt.which : event.keyCode;

        if (
        //0~9
        charCode >= 48 && charCode <= 57 ||
           //number pad 0~9
           charCode >= 96 && charCode <= 105 ||
        //backspace
           charCode == 8 ||
        //tab
        charCode == 9 ||
        //enter
        charCode == 13 || 
        //left, right, delete..
        charCode >= 35 && charCode <= 46
        )
        {
        //make sure the new value below 20
        if(parseInt(this.value+String.fromCharCode(charCode), 10) <= 20) 
            return true;
        }

        evt.preventDefault();
        evt.stopPropagation();

        return false;
    }

http://jsfiddle.net/3StSM/2/

It also works fine with:

  <input id="numIpt" type="number" min="0" max="20" maxlength="2" />
查看更多
Rolldiameter
4楼-- · 2019-09-05 16:16

Should be able to do something like this:

if (input.value < 0) input.value = 0;
if (input.value > 20) input.value = 20;

Simple as that if that's what you mean.

You could get this to run when the value for the input changes (onChange) that way they can see the limit.

Full function:

HTML:

<input type="text" onchange="limiter(this);" />

Javascript:

function limiter(input) {
   if (input.value < 0) input.value = 0;
   if (input.value > 100) input.value = 100;
}

Working Demo

查看更多
登录 后发表回答