2
votes

I want to toggle a radio button on click, but it always return true, and not unchecked. I want to call a function when radio is checked and run another function when unchecked, how can I do this?

$('input[type="radio"]').click(function() {
  console.log($(this).is(':checked'))
  if ($(this).is(':checked')) {
    $(this).attr('checked', false)
  } else {
    $(this).attr('checked', true)
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="ch"/>
<input type="radio" name="ch"/>
2
It's compulsory using radio button you can go with checkbox because normaly radio button used for single selection?jishan siddique
Don't see why you'd want to 'hack' a radio button to have this behaviour. Use a checkbox.Rory McCrossan
@RoryMcCrossan Because I want to use radio button, I need to use. I used radio button, that user can select a, or b, or just unselect a or b, also I need to radio UIdanny cavanagh
You can make a checkbox look like a radio button using CSS. Then you don't need any JS at all.Rory McCrossan
Ok, it's the 'neither' case that's the issue then. The toggle-able radio is a solution to this, however it's not standard and most user's wouldn't expect it. As such it's not a great UX decision. A better alternative may be a drop down with all three options. Alternatively use a standard radio control and have A/B/Neither as options.Rory McCrossan

2 Answers

4
votes

No, you can not do this like that, you should first detect if it's checked or not, I used a variable checked

function f1() {
  console.log('run 1st func!')
}

function f2() {
  console.log('run 2nd func!')
}

let checked = true
$('input:radio').click(function() {
  let bu = $(this);
  checked = !checked
  checked ? bu.prop('checked', !this.checked) + f1() :
    bu.prop('checked', this.checked) + f2()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" />
2
votes

You can use .prop() combine with isChecked variable to achieve it.

var isChecked = false;
$('input[type="radio"]').click(function() {
  $(this).prop('checked', !isChecked);
  isChecked = !isChecked;
  
  if(isChecked) f1();
  else f2();
  
});

var f1 = function(){
  console.log("F1");
};

var f2 = function(){
  console.log("F2");
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" />

Updated

You can also use 2 radio buttons like this

$('input[type="radio"]').click(function() {
  var value = $(this).filter(":checked").val();
 
  if(value === 'f1') 
    f1();
  else 
    f2();
  
});

var f1 = function(){
  console.log("F1");
};

var f2 = function(){
  console.log("F2");
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="my_radio" value="f1" /> <label>F1</label>

<input type="radio" name="my_radio" value="f2" /> <label>F2</label>