I need to do something similar to JQuery Sync Selected Radio Button between 2 radio button groups.
I have 2 radio groups –
<input type="radio" name="radio_A" id="radio_A_1" value="1" />1st
<input type="radio" name="radio_A" id="radio_A_2" value="2" />2nd
<input type="radio" name="radio_B" id="radio_B_1" value="1" />1st
<input type="radio" name="radio_B" id="radio_B_2" value="2" />2nd
When radio_A_1 is checked, I need radio_B_2 synced/checked. The relationships would be-
radio_A_1=>radio_B_2
radio_A_2=>radio_B_1
radio_B_1=>radio_A_2
radio_B_2=>radio_A_1
Using the answer provided #8804502
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]');
console.log(index);
$('input[name=radio_B]:eq(' + index + ')').attr('checked','checked');
});
I get same=>same, but only when A changes-
radio_A_1=>radio_B_1
radio_A_2=>radio_B_2
So if I copy it, changing it if from A=>B to B=>A–
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]');
console.log(index);
$('input[name=radio_B]:eq(' + index + ')').attr('checked','checked');
});
$('input[name=radio_B]').change(function() {
var index = $(this).index('input[name=radio_B]');
console.log(index);
$('input[name=radio_A]:eq(' + index + ')').attr('checked','checked');
});
I get same=>same, when either A or B changes –
radio_A_1=>radio_B_1
radio_A_2=>radio_B_2
radio_B_1=>radio_A_1
radio_B_2=>radio_A_2
How can I sync them 1=>2/2=>1, instead of 1=>1/2=>2? And can it be done with 1 block of code, instead of 2?
You need to add some code to take the
indexof the element just clicked and set it to0if it is1, or1if it is0. The first way that came to mind is as follows:Demo: http://jsfiddle.net/cTQeJ/1/
Though you could also try:
(Or the following demo uses kind of a fun hack if you like to make your code confusing: http://jsfiddle.net/cTQeJ/)
If you can modify the html slightly it is pretty easy with a single, short code block. Try a change like this:
I’ve added a
data-syncattribute to each radio button (and removed theidattribute since it wasn’t being used, but obviously you can leave that in if needed). Then you can write a simple function like this:…that basically says whenever any of the radio buttons is checked, find all other radio buttons with a
data-syncattribute of the same value and check them too.Note that this will work with more than two groups, as shown in this demo: http://jsfiddle.net/cTQeJ/2/