Search code examples
htmlradio-buttonradiobuttonlistradio-group

Grouping radio buttons together with a containing element?


The standard way to group radio buttons together is to assign each one a name attribute, and set each one in a certain group to the same "group name" like so:

<p>
    Group 1:<br>
    <input type="radio" name="group1" value="val1">
    <input type="radio" name="group1" value="val2">
</p>
<p>
    Group 2:<br>
    <input type="radio" name="group2" value="val3">
    <input type="radio" name="group2" value="val4">
</p>

However, having to come up with a different "group name" is a real pain when you're developing some partial code for web pages that could be used multiple times on the page. It would be much nicer if you could instead group the radio buttons together with a surrounding element, something like this:

<p>
    Group 1:<br>
    <radiogroup>
        <input type="radio" value="val1">
        <input type="radio" value="val2">
    </radiogroup>
</p>
<p>
    Group 2:<br>
    <radiogroup>
        <input type="radio" value="val3">
        <input type="radio" value="val4">
    </radiogroup>
</p>

Is something like this possible? Otherwise if my partial code is included twice on a page, the 2 instances of the first 2 inputs will all be included in the same group, and the 2 instances of the second 2 inputs will all be included in the same group. What I want, though, is 4 groups; 2 groups per partial include.


Solution

  • There doesn't seem to be a way to do this. What I ended up doing in the end was generating a new GUID for each partial and appending it to the name attribute of the radio buttons in that partial.