Recently at StatsMix we ran across a small issue where it was important to have two separate radio button groups act as one. Normally I would relegate this to a back-end programming issue, but sometimes handling things on the front end is the only way.
To that end, I whipped up this simple script in jQuery that does the trick and is so far testing well in all of our target browsers. The HTML would look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <form> <p class="radiogroup"> <!-- This is one radio group --> <input type="radio" name="group1" value="1" /> Item 1<br /> <input type="radio" name="group1" value="2" /> Item 2<br /> <input type="radio" name="group1" value="3" /> Item 3<br /> <!-- This is a separate radio group --> <input type="radio" name="group2" value="1" /> Item 4<br /> <input type="radio" name="group2" value="2" /> Item 5<br /> <input type="radio" name="group2" value="3" /> Item 6 </p> </form> |
And the script looks like this:
1 2 3 4 5 6 7 8 9 10 11 | <script type="text/javascript"> $(document).ready(function() { // Turn multiple radio groups into one $('form').delegate('.radiogroup :radio', 'click', function() { $parent = $(this).closest('.radiogroup'); $(':radio', $parent).attr('checked', false); $(this).attr('checked', true); }); }); </script> |
Basically the script detects the click action within a set of radio buttons wrapped with a parent element with a class of ‘radiogroup’. It then does a blanket uncheck on all radio buttons inside the wrapper. Finally it adds checked=”true” to the radio button that was clicked.
Hope this is helpful. Happy coding!
