0
I want to create an extension for Google Chrome that checks the status of a CPF, but I can’t get the button to run the function. How do I get him to execute?
document.addEventListener('DOMContentLoaded', function verificar(){
document.querySelector('#btn').addEventListener('click', function verificar(){
var cpf = document.getElementById("cpf").value.substring(8, 9);
})
function verificar() {
var cpf = document.getElementById("cpf").value.substring(8, 9);
if (cpf == "0") alert("Rio Grande do Sul");
else if (cpf == "1") alert(" Distrito Federal – Goiás – Mato Grosso – Mato Grosso do Sul – Tocantins ");
else if (cpf == "2") alert(" Pará – Amazonas – Acre – Amapá – Rondônia – Roraima");
else if (cpf == "3") alert(" Ceará – Maranhão – Piauí");
else if (cpf == "4") alert(" Pernambuco – Rio Grande do Norte – Paraíba – Alagoas ");
else if (cpf == "5") alert(" Bahia – Sergipe ");
else if (cpf == "6") alert("Minas Gerais ");
else if (cpf == "7") alert("Rio de Janeiro – Espírito Santo");
else if (cpf == "8") alert("São Paulo");
else if (cpf == "9") alert("Paraná – Santa Catarina");
}
})
<!DOCTYPE html>
<html lang="pt-br">
<head>
<script src="cpfteste.js"></script>
<title>CPF</title>
</head>
<body>
<input id="cpf" type="text">
<button id="btn">Verificar</button>
<div id="res">
</div>
</body>
</html>
I made the change you specified, without Domcontentloader, but now the error it returns is "Uncaught Typeerror: Cannot read Property 'addeventlistener' of null at cpfteste.js:4" I wonder if it can be this time?
– Vinicius
Your querySelector did not find the DOM button, did you put the id on the button? Make a console.log(Document.querySelector('#btn'))
– Daniel Mendes
I put yes, "<button id="btn" >Check</button> " Sorry, I’m still starting to understand better the JS, how this console procedure works.log?
– Vinicius
The.log console only displays the value on the console, try using Document.getElementById("btn")
– Daniel Mendes
I tried with getElementById, but still gives the same error, by the google extensions console the message is as follows: Uncaught Typeerror: Cannot read Property 'addeventlistener' of null Context index.html Stack tracking cpfteste.js:1 (anonymous function) "Document.getElementById("btn"). addeventlistener(click, check);"
– Vinicius
Vinicius, do the following, import your js script after body.
– Daniel Mendes