Skip to content Skip to sidebar Skip to footer

Limiting Number Value In An Input Tag With Javascript

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:

Solution 1:

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:

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

Javascript:

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

Working Demo

Solution 2:

If you need to support old browsers, try this:

functionForNumbers(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 20if(parseInt(this.value+String.fromCharCode(charCode), 10) <= 20) 
            returntrue;
        }

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

        returnfalse;
    }

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

It also works fine with:

  <inputid="numIpt"type="number"min="0"max="20" maxlength="2" />

Solution 3:

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

<inputtype="number"min="1"max="20" />

Post a Comment for "Limiting Number Value In An Input Tag With Javascript"