Mask for Note Field - 10 or 5.5

3

I'm looking for a script in jQuery to make a mask:

When you type 10 , the format field for 10,0 and when it is another note such as 6,5 , leave it.

As an example below.

I need you to delimit the moment you type and not after you click out of the field.

    
asked by anonymous 16.09.2015 / 14:58

2 answers

4

Look, I'm going to post a suggestion, where the mask always has a decimal place and allows only numbers between 0 and 10.

var notas = document.getElementsByClassName("nota"); 

var onNotaInput = function (event) {
  var regexp = new RegExp("[^0-9]", "g");
  var value = event.target.value.replace(regexp, "");
  value = parseInt(value) / 10;
  if (value >= event.target.min && value <= event.target.max) {
    event.target.dataset.value = value;
  } else {
    value = parseFloat(event.target.dataset.value);
  }
  if (isNaN(value)) {
    value = 0;
  }

  event.target.value = value.toLocaleString(undefined, { minimumFractionDigits: 1 });
};

[].forEach.call(notas, function (nota) {
  nota.addEventListener("input", onNotaInput);
});
<label>
  Nota 01:
  <input class="nota" type="text" min="0" max="10" />
</label>
<br />
<label>
  Nota 02:
  <input class="nota" type="text" min="0" max="10" />
</label>
<br />
<label>
  Nota 03:
  <input class="nota" type="text" min="0" max="10" />
</label>
<br />
<label>
  Nota 04:
  <input class="nota" type="text" min="0" max="10" />
</label>
    
16.09.2015 / 17:24
4

If I understand correctly, you want to format the field with a decimal place. Try this code:

$("#valor").on("change", function()
{
    this.value = Number(this.value.replace(",", ".")).toFixed(1).replace(".", ",");
});

Fiddle

Update

The closest I got with masked input was this:

$.mask.definitions['~']='([0-9] )?';
$("#valor").mask("~9,9", {placeholder: " "});

Fiddle

Based on in this answer .

But the mask got a * osta and I could not limit the number to 10.

Update 2

Making a mask in your hand, specific to your case, I came up with this code:

$("#valor").on("keyup", function(e)
{
    var code = (e.keyCode || e.which);

    // do nothing if it's an arrow key or backspace
    if(code == 37 || code == 38 || code == 39 || code == 40 || code == 8) {
        return;
    }

    var num = Number(this.value.replace(",", "."));

    if (this.value.replace(",", "").length > 2) num = num * 100;

    var value = (num <= 10 ? num : 10);

    this.value = value.toFixed(1).replace(".", ",");
});

Fiddle

    
16.09.2015 / 15:07