Pick radio button value and check what is selected

Asked

Viewed 1,781 times

-1

I have a form with a radio button with Individual and legal person. I want that if the person button is selected change the label attribute from html to CPF otherwise CNPJ, and apply the masks according to the selection.

I couldn’t find anything specific about it. I’m trying to do with PHP.

You can do this with PHP or just JS?

2 answers

1

Changes in the DOM in real time, can only be done through the javascript, follows an example from your case.

let tipoPessoa = document.querySelectorAll('input[name="tipoPessoa"]');

let cpf = document.querySelector('#cpf');
let cnpj = document.querySelector('#cnpj');

tipoPessoa.forEach(function(value){

value.onclick = function(event){

  cnpj.style.display = 'none';
  cpf.style.display = 'none';
  
  document.querySelector('#'+event.target.value+'').style.display = 'block';
  
}

})
#cpf {display: none;}
#cnpj {display: none;}
<input type="radio" name="tipoPessoa" value="cpf">Pessoa Física<br>
<input type="radio" name="tipoPessoa" value="cnpj">Pessoa Jurídica<br>

<input type="text" id="cpf" placeholder="Digite seu CPF"><br>
<input type="text" id="cnpj" placeholder="Digite seu CNPJ">

1

Put the code so that we can base ourselves on what you want. And how much the question is best to do with javascript. as the example below.

var radio = document.getElementsByName("check");

function funcao(){
  for(var i = 0; i < radio.length; i++){

    if (radio[i].checked && radio[i].value == "Pessoa Física") {
      document.getElementById("labelCPF").style.display = "block";
      document.getElementById("cpf").style.display = "block"
      
      document.getElementById("labelCNPJ").style.display = "none";
      document.getElementById("cnpj").style.display = "none"

    } else if (radio[i].checked && radio[i].value == "Pessoa Jurídica") {
      document.getElementById("labelCNPJ").style.display = "block";
      document.getElementById("cnpj").style.display = "block"

      document.getElementById("labelCPF").style.display = "none";
      document.getElementById("cpf").style.display = "none"

    }
  }
}
<h3>Tipo pessoa</h3>
<div id="tipoPessoa" onchange="funcao()">
<label>Pessoa Física</label>
<input type="radio" name="check" value = "Pessoa Física">
<label>Pessoa Jurídica</label>
<input type="radio" name="check" value = "Pessoa Jurídica"> 
</div>


<label style="display: none" id="labelCPF">CPF:</label>
<input type="text" id = "cpf" placeholder="CPF" style="display: none">

<label style="display: none" id="labelCNPJ">CNPJ:</label>
<input type="text" id = "cnpj" placeholder="CNPJ" style="display: none">

As for the mask take a look at this guy here: Masks in Jquery

Browser other questions tagged

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