-2
I’m trying to create a Cpf javascript mask but my code is not applied to the input, but when I give a console.log() the code is being applied to the console.
My input:
<input id="cpf" onblur="codigo.colocaMascara()" type="text" class="form-control" required />
Javascript code:
class Codigo {
colocaMascara() {
let cpf = document.querySelector('#cpf');
cpf.addEventListener('input', (text) => {
let resultado = text.target.value;
return resultado
.replace(/\D/g, '')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d{1,2})/, '$1-$2')
.replace(/(\-d{2})\d+?$/, '$1')
});
}
}
<input id="cpf" onblur="codigo.colocaMascara()" type="text" class="form-control" required />
Take a look at this question: https://answall.com/questions/218989/formatr-sequentiallynum%C3%A9rica-in-format-Cpf-with-separators-using-javascript
– Daniel Mendes
<input id="Cpf" onkeyup="codigo.colocaMask()" type="text" class="form-control" required />
– ludu25
Does this Answer your Question? Format numerical sequence in CPF format with tabs using javascript
– DaviAragao
I already took a look at those, but I was wondering what’s wrong with my code. It’s just not showing in the input.
– ludu25
You are Return the result and not assigning the input value
– Benilson
codigo is not defined
; you set the classCodigo
, but at no time did you urge her to create the objectcodigo
used in the<input>
.– Woss
Complementing what @Woss commented... If your class only has this, it doesn’t need it, it would be simpler to just have the object (creating with
const codigo = { colocaMascara: () => { /* ... */}}
). If you want to keep the class would be interesting the variablecpf
is thus accessible by all methods and thequerySelector
will not be called all the time, can still receive this reference to the HTML element in the constructor, doing a control inversion and decoupling your code– Costamilam
yeah, I set up the class yes, I just forgot to put it here. But thank you all.
– ludu25