How to erase the symbols of a CPF in an input?

Asked

Viewed 94 times

3

I’m creating a website that asks for the name and the person’s number the CPF has to be in format xxx.xxx.xxx-xx. And by pressing the button he registers the person (The data is only displayed on the screen). But I decided to create a script that automatically completes the CPF symbols when the user starts typing that is the . and the -. But the script yes, it works autocomplete the symbols only that when trying to erase does not erase, look at the code this is a prototype of the project script that I am creating.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>

    <input id="box" type="text" maxlength="14">

    <script>

      var box = window.document.querySelector("#box");

      box.addEventListener("input", function()
      {
          switch (box.value.length)
          {
              case 3:
                  box.value += ".";
                  break;
              case 7:
                  box.value += ".";
                  break;
              case 11:
                  box.value += "-";
          }
      });

    </script>
  </body>
</html>

Note, that when typing the CPF I cannot erase the symbols because I am using the event input in the input. So each time I modify the data within the input the event input will be called and fall there in the switch and will execute the case 11:, that’s because the box.value.length will equal 11. So every time you try to erase, you can’t because it will always fall on case 11:, then this is my problem I can’t erase the symbols. How do I delete them? , without letting use the event input ?, because I need this event in the script to be able to automatically update the live symbols for the user, so he will not take the work of digitales and will further improve his experience with my site.

  • 1

    In my opinion you are trying to reinvent the wheel, there is already lib for this https://igorescobar.github.io/jQuery-Mask-Plugin/

  • I think he doesn’t want a lib, but simple and pure script

  • 1

    I looked is very interesting this lib, but the problem is that I wanted with pure js.

  • is a great idea @Lucasmiranda, but what if he doesn’t want to use jquery? in his code is using pure javascript

2 answers

3

You can add other cases by cutting the string at the position where the characters are, I used in the example the method replace():

var box = window.document.querySelector("#box");

box.addEventListener("input", function() {
  switch (box.value.length) {
    case 3:
      box.value += ".";
      break;
    case 7:
      box.value += ".";
      break;
    case 11:
      box.value += "-";
      break;
    case 12:
      box.value = box.value.substr(0, box.value.length-1);
      break;
    case 8:
      box.value = box.value.substr(0, box.value.length-1);
      break;
    case 4:
      box.value = box.value.substr(0, box.value.length-1);
  }
});
<input id="box" type="text" maxlength="14">

NOTE: When characters are deleted . or -, it is necessary to delete one more number in order to be able to re-fill the field with values.

  • 1

    Oops, thanks a lot, thanks a lot!

  • Your solution does not work well when you have just deleted a dash and want to re-type numbers, or when you have just entered a dash and want to delete it right away.

  • @Isac Yes, your example is much more complete and is what should be the answer really, I just implemented a way applying its logic using marry. I will put a remark on the answer, that after deleting the character it is necessary to delete one more to be able to fill the field again.

2


I suggest a more elaborate solution, but more robust and flexible, that does not cause you problems when deleting a number just getting the trace at the end, or when you have just deleted the trace and want to add another number.

In the solution I present, I extract the numbers from the box with a simple regular expression, with /\d/g and apply the insertion characters at the right points, using a pre-built dictionary for this purpose.

Example:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <input id="box" type="text" maxlength="14">

    <script>
      const box = document.querySelector("#box");
      const insercoes = {
        3: ".",
        7: ".",
        11: "-"
      };

      box.addEventListener("input", function(e){
          //obter os números ou array vazio se não houver nenhum número digitado
          let nums = box.value.match(/\d/g) || []; 
          
          for (let posicaoInserir of Object.keys(insercoes)){ //para cada ponto de inserção
            //se o tamanho dos numeros é suficiente para esta posição de inserção
            if (nums.length > parseInt(posicaoInserir)){
              //inserir o caratere na posição certa
              nums.splice(parseInt(posicaoInserir), 0, insercoes[posicaoInserir]);
            }
          }
          
          box.value = nums.join(""); //colocar o novo array na caixa
      });
    </script>
  </body>
</html>

Remove works properly without being required to do anything else due to testing nums.length > parseInt(posicaoInserir). If you have the number of characters up to the stroke it does not apply any trait and therefore allows you to remove. Only when it has more characters does it apply the insertion character in the middle.

Browser other questions tagged

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