Jquery mask that accepts values up to 10.0

Asked

Viewed 45 times

0

As I would for a text field to receive values up to 10.0 and to have a mask like this: 1.0, 2.3, 10.0, that is, when the value is less than the limit 10.0, the decimal has only 1 number. Is this possible with Jquery? I have a script that sums all fields, you can include 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>
  • 10.0, could be 10.01, 10.02, etc? Or 10.0 is the limit, that is after the flowing point nothing can be above 0, even if it is a number well "broken"?

  • Hello William. That, 10.0 would be the limit. I will adjust my post ;)

  • He can accept numbers as 9.99999998?

  • It would be exactly for school grade. I believe it would have to be 9.9 and 10.0.

  • I get it, so decimal is always one digit, I just need to confirm this

  • that’s right. The decimal would be only 1 digit

Show 1 more comment

1 answer

2


If the decimal place has a single digit limit, you can first use maxlength in the <input> 4-digit (largest expected number is 10.0 - since it contains the "mascara") and then apply a function with very simple regex.

However the input is run at all times, which causes a number of conflicts, I suggest opt for the event blur, which is only executed the moment the element loses focus, another important thing is that for inputs that already see pre-populated it is necessary to execute the event part, 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'>

  • Note [1]: The third parameter alvo is opitional, it serves to chance you want to isolate the event for a specific element, type, suppose there are 2 groups of elements or you want to apply the mask on an element within an IFRAME, just adjust this 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) from running repeatedly the trigger, that is, with the clearTimeout+setTimeout it will ensure that within the 10ms range it is only executed once, so this way avoiding parallel executions.

  • Note [3]: note that I applied the maxlength to avoid the person typing too much.

  • 1

    Thank you William.

Browser other questions tagged

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