JQuery mask that accepts values up to 10.0

0

How would I make a text field receive values up to 10.0 and have a mask like this: 1.0, 2.3, 10.0, that is, when the value is less than the 10.0 limit, the decimal has only 1 number. Is this possible with JQuery? I have a script that adds all the fields, how do I include it inside this script?

<input type='text' name='NotaI[]'  id='justificativa' class='mascara md-form-control'  value='".$notaProvas."'>
<input type='text' name='NotaII[]'  id='justificativa' class='mascara md-form-control'  value='".$notaProvas."'>
<input type='text' name='NotaIII[]'  id='justificativa' class='mascara md-form-control'  value='".$notaProvas."'>

<script>
     $("[name^='NotaI']").on("input", function(){

           var parent = $(this).closest("tr");

           var valorA = $("[name='NotaI[]']",parent).val() || 0;
           var valorB = $("[name='NotaII[]']",parent).val() || 0;
           var valorC = $("[name='NotaIII[]']",parent).val() || 0;

           var valor1 = parseFloat(valorA.toString().replace(',', '.'));
           var valor2 = parseFloat(valorB.toString().replace(',', '.'));
           var valor3 = parseFloat(valorC.toString().replace(',', '.'));

          /*
           var vazios = 0;

               $(":input.md-form-control").each(function(i, val) {
                  if ($(this).val() == '') {
                     vazios++;
                  }
               });
           console.log(matches);
         */
         var campos = $("[name^='NotaI']", parent);

          // conta apenas os vazios
          var vazios = campos.filter(function(){
              return $(this).val();
          }).length;

          var somar = ((valor1+valor2+valor3)/vazios).toFixed(1);
          $("[name='NotaFinal[]']", parent).val(somar);
     });
</script>
    
asked by anonymous 13.08.2018 / 20:55

1 answer

2

If the decimal place is limited to a single digit, you can first use maxlength in the <input> of 4 digits (highest expected number is 10.0 - since it contains the "mask") and then apply a function with very simple regex.

However input is executed at all times, which causes a series of conflicts, I suggest opting for the blur event, which is only executed the moment the element loses focus, another important thing is that for the inputs that already pre-filled it is necessary to execute the part of the event, something like:

$('[name^='NotaI']').each(function () {
    this.value //Aplica a mascara
});

function mascaraPontoFlutuante(query, fixo, alvo) {
    var mascara;
    alvo = alvo || document;
    
    //Executa ao carregar a página
    $(function () {
       $(query, alvo).each(function () {
            trigger(this);
       });
    });
    
    //Atualiza quando o usuário tentar mudar o valor
    $(alvo).on("blur", query, function () {
        if (mascara) clearTimeout(mascara);
        
        mascara = setTimeout(trigger, 10, this);
    });
    
    function trigger(elemento) {
         var valor = elemento.value;
        //Se o formato estiver correto (regex) então não executa nada
        if (/^\d{1,2}\.\d$/.test(valor)) return;
        
        //Se o formato não for o esperado então ajusta
        
        //Remove tudo que não for numero ou ponto
        valor = parseFloat(valor.replace(/[^\d]/g, ""));

        //Se for um value vazio ele irá virar NaN, então isto transforma em 0
        if (isNaN(valor)) valor = 0;
        
        //Se o valor é maior que 10 então transforma em 10 novamente
        if (valor > 10) valor = 10;
        
        //Fixa o valor
        elemento.value = valor.toFixed(fixo);
    }
}

//Aplica a mascara e define o ponto fixo como 1
mascaraPontoFlutuante("[name^='NotaI']", 1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' name='NotaI[]'  id='justificativa' class='mascara md-form-control'  value='1000' maxlength='4'>

<input type='text' name='NotaII[]'  id='justificativa' class='mascara md-form-control'  value='2' maxlength='4'>

<input type='text' name='NotaIII[]'  id='justificativa' class='mascara md-form-control'  value='9' maxlength='4'>
  
    The third parameter alvo is optional, it is for you to want to isolate the event for a specific element, type, suppose there are 2 groups of elements or you want to apply the mask to an element within an IFRAME, you just need to adjust that third variable.

      
  • Note [2] : The setTimeout for those who do not understand, this is used to prevent many events (which may occur due to other scripts ) execute trigger repeatedly, that is, with clearTimeout + setTimeout it will ensure that within the 10ms range it is only executed once, thus avoiding parallel execution.

  • >      
    
13.08.2018 / 21:18