Get value from the radio button and check what is selected [duplicate]

-1

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

I did not find anything specific about. I'm trying to do with PHP.

Is it possible to do this with PHP or just with JS?

    
asked by anonymous 21.08.2018 / 14:31

2 answers

0

Changes in DOM in real time, can only be done through javascript , follow an example of 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">
    
21.08.2018 / 14:50
0

Put the code so we can build on what you want. And as for the question the best is 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">

How much does the mask take a look at this guy here: Jquery Masks

    
21.08.2018 / 15:22