Max length in input type number html

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 because it is a value in addition to the 15.4 database I need this input stay with the maxlength of 15.4 Anybody know ?

    
asked by anonymous 18.03.2018 / 22:26

2 answers

1

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

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

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

But of course typing manually will be possible to enter a much larger number, so you can use the events keyup and blur , eg:

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">
    
18.03.2018 / 22:44
0

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

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

In this case the input goes from 0 to 15.4 going one by one.

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

    
18.03.2018 / 22:33