Score in Javascript output

Asked

Viewed 70 times

2

I’m trying to solve a problem where the user entered apenas the Cpf numbers in a input and, next to it, it will be displayed in the correct format of CPF (xxx.xxx.xxx-xx).

However, someone knows why the score appears, but after I keep typing the score goes away?

var inCPF = document.getElementById("inCPF");
var outCPF = document.getElementById("outCPF");

function formatar() {
    var cpf = inCPF.value;

    if (cpf.length == 3 || cpf.length == 7) {
        cpf += ".";
    } else if (cpf.length == 11) {
        cpf += "-";
    }

    outCPF.textContent = cpf;
}


inCPF.addEventListener("keyup", formatar);

1 answer

4


This problem is happening because in your code is added the . only when size is 3 or 7: if (cpf.length == 3 || cpf.length == 7). And the - only when size is 11: else if (cpf.length == 11). In other cases it will not add anything, that is, in the end it will not add the elements.

What I recommend to do is to catch the inCPF, remove undesirable symbol values and place characters, . and -, among them.

Would look that way:

var inCPF = document.getElementById("inCPF");
var outCPF = document.getElementById("outCPF");

function formatar() {
    var cpf = inCPF.value;
    //retira os caracteres indesejados e adiciona os novos
    cpf = cpf.replace(/\D/g, "").replace(/^(\d{3})(\d{3})?(\d{3})?(\d{2})?/, "$1.$2.$3-$4");
    //Aqui limita os caracteres exibidos no outCPF
    if(cpf.length <= 14){
        outCPF.textContent = cpf;
    }
}


inCPF.addEventListener("keyup", formatar);
<input id="inCPF" maxlength="14">
<p id="outCPF"></p>

EDIT

I made the changes suggested in the comments. I even limited the code to a maximum of 14 characters.

  • 1

    It is possible to do this without using Regexp?

  • I don’t know any other way to format the number while typing without Regexp or jQuery. But if you want to do the formatting after typing the full number, there are several other ways.

  • 1

    Details: [\d] is the same as \d (usually when there is only one element between brackets, it is still, but there is no advantage to use the brackets so use without: \d{3}, etc), and instead of [^0-9] can use \D

  • 1

    is accepting something like 123.456.789-01234

  • I edited according to your suggestions.

Browser other questions tagged

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