1

$(function() {
  $("#aa").click(function() {
    $("#aa2").attr("checked", true);
  });
  $("#bb").click(function() {
    $("#bb2").attr("checked", true);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='radio' name='a' id='aa'/>aa
<input type='radio' name='a' id='bb'/>bb
<br>
<input type='radio' name='b' id='aa2'/>aa2
<input type='radio' name='b' id='bb2/'>bb2

When I click aa, aa2 checked, click bb, bb2 cheked. However, then click aa, bb2 remains checked, and aa2 is not checked

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Jason Z
  • 265
  • 1
  • 6
  • 12

2 Answers2

1

You likely need to use the .prop() method instead of the .attr() method.

When using .attr(), you are setting an attribute. When the attribute is set, the property will be set. In your case, if the attribute has already been set, it will not change the property again, therefore you should just change the property using .prop() to begin with.

As a side note, I'd suggest listening to the change event of the radio elements rather than the click event.

Example Here

$("#aa").on('change', function () {
    $("#aa2").prop("checked", "checked");
});
$("#bb").on('change', function () {
    $("#bb2").prop("checked", "checked");
});

See .prop() vs .attr().

Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Could shrink it down even further to `$("input[name='a']").on('change', function () { $("input[name='b']").eq($(this).index()).prop("checked", "checked"); });` – j08691 Feb 21 '15 at 03:53
0

This should work for you

$(function() {
  $("input[name=a]").change(function() {
    $("input[name=b]").removeAttr('checked');
    $("input[name=b]").filter('[value='+$(this).val()+']').attr('checked', true);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='radio' name='a' value="1" />aa
<input type='radio' name='a' value="2" />bb
<br>
<input type='radio' name='b' value="1" />aa2
<input type='radio' name='b' value="2" />bb2
Abraham Romero
  • 1,047
  • 11
  • 22