I wrote a form with these elements:
<div>
<label for="radio_pessoa_fisica" id="label_cpf_req">
<input name="pessoa" id="radio_pessoa_fisica" type="radio" value="fisica" required>
Pessoa Física
</label>
<label for="radio_pessoa_juridica" id="label_cnpj_req">
<input name="pessoa" id="radio_pessoa_juridica" type="radio" value="juridica" required>
Pessoa Jurídica
</label>
</div>
<div>
<label for="cpf_req">
CPF
<input id="cpf_req" type="text" placeholder="000.000.000-00" required maxlength="14" pattern="([0-9][.-]?){3,11}">
</label>
<label for="cnpj_req" id="label_cnpj_req" >
CNPJ
<input id="cnpj_req" type="text" placeholder="00.000.000/0000-00" required maxlength="18">
</label>
</div>
At the end, before closing the body, the tag <script>
that calls the following code:
function radio_pessoa_change() {
var pfis = document.getElementById("radio_pessoa_fisica").checked;
document.getElementById("label_cpf_req").style.display = pfis ? "block" : "none";
document.getElementById("label_cnpj_req").style.display = pfis ? "none" : "block";
document.getElementById("req_rep").disabled = !pfis;
if (!pfis) {
document.getElementById("req_rep").checked = true
}
}
document.getElementById("radio_pessoa_fisica").addEventListener("change", radio_pessoa_change);
document.getElementById("radio_pessoa_juridica").addEventListener("change", radio_pessoa_change);
document.getElementById("radio_pessoa_fisica").checked = true;
However, when I navigate to the form page, the #radio_pessoa_fisica
input is checked by the script, but the event handler is not called, and both text inputs, #cpf_req
and #cnpj_req
are visible.
Only by clicking the radio inputs on the page itself is the function called and doing what is expected.
Can anyone explain to me why this happens, and if possible, help me get the desired effect (that function radio_pessoa_change()
is executed and hides the input #cnpj_req
Please, thank you for your responses to pure JavaScript.