Change the checked value of an input type = 'radio'

0

I have two radio inputs

<input id="tab-1" type="radio" value="juridica" name="tab" class="sign-in"><label for="tab-1"class="tab">Jurídico</label>                                                                                 
<input id="tab-2" type="radio" value="fisica" name="tab" class="sign-up" checked="checked"><label for="tab-2"class="tab">Físico</label>

and I want to do a check for which is selected, by default, the physical is already checked.

if ($("#tab-1").prop("checked")){
   document.getElementById('cpf').required = true;
   document.getElementById('nome-completo').required = true;
   document.getElementById('cnpj').required = false;
   document.getElementById('razao-social').required = false;
} else {
   document.getElementById('cpf').required = false;
   document.getElementById('nome-completo').required = false;
   document.getElementById('cnpj').required = true;
   document.getElementById('razao-social').required = true;
}

however, it is not working. When I select the legal does not work. It works just for the physicist, which is already pre-selected.

    
asked by anonymous 07.12.2018 / 15:18

1 answer

1

This is an example of the code for you to notice the return according to the click on the input elements

$(function(){
  $('input').on("click", function(){
	alert($("#tab-1").is(":checked"));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><inputid="tab-1" type="radio" value="juridica" name="tab" class="sign-in"><label for="tab-1"class="tab">Jurídico</label>                                                                              
<input id="tab-2" type="radio" value="fisica" name="tab" class="sign-up" checked="checked"><label for="tab-2"class="tab">Físico</label>

Notice that this way we get the Boolean result of the input.

HTML

<input id="tab-1" type="radio" value="juridica" name="tab" class="sign-in"><label for="tab-1"class="tab">Jurídico</label>                                                                              
<input id="tab-2" type="radio" value="fisica" name="tab" class="sign-up" checked="checked"><label for="tab-2"class="tab">Físico</label>

JQuery

if ($("#tab-1").is(":checked")){
   document.getElementById('cpf').required = true;
   document.getElementById('nome-completo').required = true;
   document.getElementById('cnpj').required = false;
   document.getElementById('razao-social').required = false;
} else {
   document.getElementById('cpf').required = false;
   document.getElementById('nome-completo').required = false;
   document.getElementById('cnpj').required = true;
   document.getElementById('razao-social').required = true;
}
    
07.12.2018 / 17:32