Ray
Ray

Reputation: 33

how to uncheck a group of radio buttons when one in another group is checked

I have 2 groups of radio buttons. When a button in on group is clicked any button in the other group should be unchecked, and vice versa. I tried below which works only once. The smartest way I thought would be click(). But I can't get my head around it. Any suggestions?

function uncheckRadioBtnSet(){
  if ($('[name="a"]').is(':checked')){
    $('input[name="b"]').removeAttr('checked');
    $(this).off('click');
  }else{
    $('input[name="a"]').removeAttr('checked');
    $(this).off('click');
  }
}

$("input[name='a']").click(function(){
   uncheckRadioBtnSet();
});
$("input[name='b']").click(function(){
   uncheckRadioBtnSet();
});

<input type="radio" name="a"  value="1"><br>
<input type="radio" name="a" value="2"><br>
<input type="radio" name="a"  value="3"><br>

<h6> separator </h6>

<input type="radio" name="b" value="4"><br>
<input type="radio" name="b" value="5"><br>
<input type="radio" name="b"  value="6"><br>

Upvotes: 2

Views: 1736

Answers (3)

Raman Sahasi
Raman Sahasi

Reputation: 31841

Try this nanocode :)

$("input[name='a'], input[name='b']").click(function(){
   $('input[name="'+{b: 'a',a: 'b'}[this.name]+'"]').prop("checked", false);
});

Plunker


Updated code according to new requirements

$("input[name='item_meta[313]'], input[name='item_meta[314]']").click(function(){
   $('input[name="'+{'item_meta[313]' : 'item_meta[314]', 'item_meta[314]' : 'item_meta[313]'}[this.name]+'"]').prop("checked", false);
});

However, for the sake of readability, you can also write this code as:

var obj = {
  'item_meta[313]' : 'item_meta[314]', 
  'item_meta[314]' : 'item_meta[313]'
}
$("input[name='item_meta[313]'], input[name='item_meta[314]']").click(function(){
   $('input[name="'+obj[this.name]+'"]').prop("checked", false);
});

See this updated Plunker

Upvotes: 1

Jishnu V S
Jishnu V S

Reputation: 8409

it will be ok if we use same name for all radio buttons

<input type="radio" name="a"  value="1"><br>
<input type="radio" name="a" value="2"><br>
<input type="radio" name="a"  value="3"><br>
<h6>
separator
</h6>
<input type="radio" name="a" value="4"><br>
<input type="radio" name="a" value="5"><br>
<input type="radio" name="a"  value="6"><br>

Upvotes: 0

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

You can use this:

$("input[name='a']").click(function(){
   $('input[name="b"]').prop("checked", false);
});
$("input[name='b']").click(function(){
   $('input[name="a"]').prop("checked", false);
});

Demo: https://jsfiddle.net/iRbouh/xn61vs1q/

Upvotes: 0

Related Questions