Incompatibility between onkeyup and date mask?

Asked

Viewed 626 times

2

I’m having a problem using onkeyup in a date mask which is as follows: when I try to use Backspace to modify the date, I cannot pass the bar (only the button is pressed). The bar keeps disappearing and appearing (do the test here on fiddle, or below in "Run code snippet", type any date and then try to delete).

This only happens if I’m using onkeyup, with onkeypress is normal (but I have to use onkeyup, because it also serves to enable a button if the date validates, and it has to be when you finish typing, and not when you lose focus...).

     function formatar(mascara, documento) {
                var i = documento.value.length;
                var saida = mascara.substring(0, 1);
                var texto = mascara.substring(i);
                if (texto.substring(0, 1) != saida) {
                    documento.value += texto.substring(0, 1);
                }
            }
<input class="form-control" type="text" maxlength="10" placeholder="dd/mm/aaaa" onkeyup="formatar('##/##/####', this)" name="Tinsem3" id="Cinsem">

There’s a way?

1 answer

1


You can make the function not run if the key is pressed backspace or delete. In this case you need to pass the event to the function and then search if the key code is 8 or Resp. 46.

onkeyup="formatar('##/##/####', this, event)"

and in Javascript

function formatar(mascara, documento, e) {
    var code = e.keyCode || e.code;
    if (code == 8 || code == 46) return;

jsFiddle: http://jsfiddle.net/k9ejqaav/

  • 1

    Thanks again Sergio! You are practically a silent partner in my project! : -) Just for the record, I also included keycodes (nice tip, btw) of the back and forward arrows (Arrow left and Arrow rigth) because I saw now that tbm were giving the same problem, and the respective line was like this: if (code == 8 || code == 46 || code == 37 || code == 39) return;.

Browser other questions tagged

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