Max length input type number html

Asked

Viewed 18,714 times

1

I have an input type number

     <div class="form-group col-md-3">
        <label class="lb">Valor total</label> 
         <input  type="number"  min="0" id="idValorTotalProdutoP" ng-model="subTotalProduto"  class="form-control"/>                     
    </div> 

and for being a value beyond the database contain 15.4 I need this input get the maxlength of 15.4 someone knows ?

2 answers

4


the maxlength works by typed characters (inputados), and not for the specific numeric format, what you can use is the attribute max="" and will have to use the step to add from 0.01 to 0.01 (or 0.1), thus:

<input class="foo" type="number" min="0" max="15.4" maxlength="4" step="0.01">

Note: the maxlength= this with the value 4 and will limit to four digits, in case the intention is something like 00.00

But of course if you type manually it will be possible to enter a much larger number, then you can use the events keyup and blur, example:

var foo = document.querySelector(".foo");

//Cria uma função que será usando no keyup e no blue
var f = maxNumber(15.4);

foo.addEventListener('keyup', f);
foo.addEventListener('blur', f);

function maxNumber(max)
{
    var running = false;
    
    return function () {
        //Para evitar conflito entre o blur e o keyup
        if (running) return;
        
        //Bloqueia multiplas chamadas do blur e keyup
        running = true;
        
        //Se o input for maior que 15.4 ele irá fixa o valor maximo no value
        if (parseFloat(this.value) > max) {
            this.value = 15.4;
        }
        
        //Habilita novamente as chamadas do blur e keyup
        running = false;
    };
}
<input class="foo" type="number" min="0" max="15.4" maxlength="4" step="0.01">

0

You can use step with the number of decimals you want to accept

Would look like this <input type="number" step="0.1" min="0" max="15.4">

In this case the input goes from 0 until 15.4 advancing from one to one decimo.

ps: The use of max and min does not prevent the user from putting a value beyond the limits manually.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.