Get value selects form_dropdown

Asked

Viewed 52 times

1

Hello, I have the following code snippet

onkeypress="mascaraMutuario(this,cnpj)

Where it is one that creates a mask for CNPJ or CPF. However, I have

<?php
    $bs = array('0' => '', '1' => 'Pessoa Física', '2' => 'Pessoa Jurídica');
    echo form_dropdown('tipo', $bs, set_value('tipo', '0'), 'class="form-control select2" id="tipo" required="required" style="width:100%;"');
?>

Where I would like that depending on the type of person selected it called my specific function, passing by parameter the CNPJ or CPF.

  • Your question is not very clear, but from what I understand, you want to modify an area of the page according to the selection of individual or legal, is this?

  • that’s exactly what

  • You should do this using javascript.

  • I would have some example of how I can do?

  • But what do you want to do on the screen?

  • who put the mask, depending on the type of person selected, on an inpput

  • I’ll do it here as your answer

Show 2 more comments

1 answer

1


I did the answer as discussed in the comments, all the code is commented for better understanding.

$(function() {
  
  // Copio os campos
  var cpf = $("#input-group-cpf").clone();
  var cnpj = $("#input-group-cnpj").clone();
  
  // Removo os campos da tela
  $("#input-group-cpf").remove();
  $("#input-group-cnpj").remove();
  
  // Adiciono como padrao o cpf
  $(".numero-documento").append(cpf);
  
  atualizaMascara();
  
  //Coloco o evento clique no radio
  $('[name="pessoa"]').on("click", function(){
  
  	// Removo os campos da tela
    $("#input-group-cpf").remove();
    $("#input-group-cnpj").remove();
  	
    // E adiciona o campo correspondente de acordo com o valor do radio
    if($(this).val() == "fisica"){
    	$(".numero-documento").append(cpf);
    }else{
    	$(".numero-documento").append(cnpj);
    }
    
    atualizaMascara();
    
  });
  
});

function atualizaMascara(){
	$(".numero-documento").find("#input-group-cpf").find("input").mask('000.000.000-00', {reverse: true});
  $(".numero-documento").find("#input-group-cnpj").find("input").mask('00.000.000/0000-00', {reverse: true});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>

<input type="radio" name="pessoa" value="fisica" checked> Pessoa Física<br>
<input type="radio" name="pessoa" value="juridica"> Pessoa Jurídica<br>

<div class="numero-documento">
  <div id="input-group-cpf">
    <label for="cpf">CPF</label>
    <input type="text" class="cpf" id="cpf"/>
  </div>

  <div id="input-group-cnpj">
    <label for="cnpj">CNPJ</label>
    <input type="text" class="cnpj" id="cnpj"/>
  </div>
</div>

  • 1

    Very good.... Thank you.

  • Please evaluate the response positively and mark as your answer ;)

Browser other questions tagged

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