Activate radio when the checkbox is true

0

I want to activate a radio at the time that my input checkbox is true, with the code I have it works well but only once, when I hit it again no.

$(document).ready(function($) { 

  $("input[type='checkbox']").click(function(event){

  var inputcheck = $(this);

  var checked = $("input[type='radio']");

  if (inputcheck.prop("checked") == true ){

  $(checked).attr('checked', true);

  } else{

  $(checked).attr('checked', false);

} }); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
asked by Avancini1 21.03.2018 в 17:23
source

2 answers

1

The problem you have is to use the $() selector constantly on an element you have already searched for, such as the case of the inputcheck that equates it to $(this) , so clean the code a bit more using ids for the elements. Also change the logic of some parts taking into account the documentation of attr () .

$(document).ready(function($) {

  $("#chk").click(function(event) {

    var inputcheck = this;
    var radio= $("#rad");
    
    if (inputcheck.checked) {
    
      radio.prop("checked", true);

    } else {

      radio.prop("checked", false);

    }
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input id="chk" type="checkbox" />
<input id="rad" type="radio" />
    
answered by 21.03.2018 / 18:09
source
0

Assuming you have a radio input and a checkbox could be something like that, I understand that when the checkbox is selected the radio is activated and when the radio is deactivated, this example can work this is the html

<input type="checkbox" id="checkbox">
<input  type="radio" id="radio" disabled>

and javascript

$(document)
  .ready(function(){
    $checkbox = $('#checkbox');
    $radio = $('#radio');
    $checkbox.click(function(event){
      var isChecked = event.target.checked;
      if(isChecked){
        $radio.removeAttr('disabled')
      } else {
        $radio.attr('disabled', true)
      }
   })
 })
    
answered by 21.03.2018 в 17:47