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

Asked

Viewed 500 times

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 make a check for which one 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 is only worked for the physical, which comes pre-selected.

  • 1

    try to do $("#tab-1").is(":checked")

1 answer

1


This is an example of the code for you to notice the return according to the click on the inputs 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>
<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>

Note that this way we can get the boolean input result.

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;
}

Browser other questions tagged

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