0

I have a feeling this is a super-basic question, but searching hasn't turned up anything.

The stripped-down HTML:

<input name="ID_1" type="radio" value="1" id="A01" /> A01<br>
<input name="ID_1" type="radio" value="2" id="A02" /> A02<br>

<input name="ID_2" type="radio" value="1" id="A01" /> A01<br>
<input name="ID_2" type="radio" value="2" id="A02" /> A02<br>

Let's say the user clicks the first radio.

Then the user clicks the third radio.

What I want is for the first radio to be unchecked...and vice versa.

Same for the second radio and the fourth radio.

Thank you!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Sung
  • 480
  • 2
  • 11
  • so if you click in the group `ID_2` no radio should be checked on `ID_1`? – lois6b Oct 24 '18 at 15:36
  • 2
    https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page Don't repeat ids – Taplar Oct 24 '18 at 15:37
  • @lois6b No -- in this scenario, the valid checks are 1 and 4 or 2 and 3. Basically, only one A01 and one A02 should be chosen. – Sung Oct 24 '18 at 15:39
  • @Taplar Ugh, I didn't know that. I wonder how else I can make this work, then. Use class instead? – Sung Oct 24 '18 at 15:40

1 Answers1

2

I changed the ids to classes. Then the logic runs when any radio button changes. It finds all the radio buttons with the same class, excludes the one that was just changed, and un-checks the other one with the same class.

$(':radio').on('change', e => {
  $('.'+ e.target.className).not(e.target).prop('checked', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<input name="ID_1" type="radio" value="1" class="A01" /> A01<br>
<input name="ID_1" type="radio" value="2" class="A02" /> A02<br>

<input name="ID_2" type="radio" value="1" class="A01" /> A01<br>
<input name="ID_2" type="radio" value="2" class="A02" /> A02<br>
Taplar
  • 24,788
  • 4
  • 22
  • 35
  • Unfortunately we are on jQuery v1.8.2...would that make a difference? – Sung Oct 24 '18 at 15:55
  • Snippet changed to v1.8.2 @Sung Easy enough to test, :) – Taplar Oct 24 '18 at 15:55
  • One thing I noticed is that if you choose first A01, then last A02, but then you choose second A02, it resets A01, too. :( – Sung Oct 24 '18 at 15:57
  • Because the radios are still governed by the inherient behavior that radio buttons enforce, that only one radio button with a shared **name** can be selected at one time. All this logic is doing is adding the additional behavior of unchecking other radio buttons with the same class. It does not, and cannot, replace the inherient browser restrictions related to radio buttons. – Taplar Oct 24 '18 at 15:58
  • Ah, you are right! I was getting this confused. Thanks so much for this totally awesome solution! – Sung Oct 24 '18 at 16:01
  • IE11 doesn't support arrow functions. Change `e => {}` to `function(e){}` – Taplar Oct 24 '18 at 16:20
  • Dude, I owe you a beer. Thank you. :) – Sung Oct 24 '18 at 16:22