Show and hide form fields of the radio type

Asked

Viewed 4,831 times

3

I have a form with two inputs of the kind radio, one with physical and other legal value. When one is selected, the fields to be filled are different from the other (mainly in PJ), so I would like to know a very practical way to display and hide the form fields when selecting one of the options.

  • You can put 2 Divs, pf and pj, with display None and when the user clicks on one of the radio’s he arrow the display block of one of these Divs

  • Pure Javascript or some framework like Angular? You need to give more details.

1 answer

3

You can do something like this, using Javascript only:

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>

Browser other questions tagged

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