Display and hide form fields of the radio type

3

I have a form with two inputs of type radio , one with individual and legal value. When one is selected, the fields to fill in are different from the other (especially in PJ), so I would like to know a very handy way to display and hide form fields by selecting one of the options.

    
asked by anonymous 24.04.2015 / 21:28

1 answer

3

You can do something like this, using just Javascript:

function tipoPessoaSel() {
  var pf = document.getElementById("opt-pf").checked;
  if (pf) {
    document.getElementById("pf").style.display = "block";
    document.getElementById("pj").style.display = "none";
  } else {
    document.getElementById("pf").style.display = "none";
    document.getElementById("pj").style.display = "block";
  }
}
<fieldset>
  <legend>Cadastro</legend>
  <div>
    <label for="opt-pf">Pessoa Física</label>
    <input id="opt-pf" checked="checked" type="radio" name="TipoPessoa" onclick="tipoPessoaSel();" />&nbsp;
    <label for="opt-pj">Pessoa Jurídica</label>
    <input id="opt-pj" type="radio" name="TipoPessoa" onclick="tipoPessoaSel();" />
  </div>
  <div id="pf">
    <div>
      <label for="cpf">Cpf</label>
      <input id="cpf" type="text" name="Cpf" />
    </div>
    <div>
      <br />Outros campos Pessoa Física...
    </div>
  </div>

  <div id="pj" style="display: none;">

    <div>
      <label for="cnpj">CNPJ</label>
      <input id="cnpj" type="text" name="Cnpj" />
    </div>
    <div>
      <br />Outros campos Pessoa Jurídica
    </div>
  </div>
</fieldset>
    
24.04.2015 / 23:24