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.
In my opinion you are trying to reinvent the wheel, there is already lib for this https://igorescobar.github.io/jQuery-Mask-Plugin/
– Lucas Miranda
I think he doesn’t want a lib, but simple and pure script
– Maury Developer
I looked is very interesting this lib, but the problem is that I wanted with pure js.
– Leandro Nascimento
is a great idea @Lucasmiranda, but what if he doesn’t want to use jquery? in his code is using pure javascript
– Ricardo Pontual