Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML nested radio buttons

Tags:

html

I have 4 radio buttons (A, B, C, D). When I click on the radio button A, there would be another 2 options - A1 and A2. The same will happen with the others. And if I choose D2, another 2 radio buttons would appear.

How can I do this in HTML?

like image 295
pulltab2kan Avatar asked Jan 22 '23 18:01

pulltab2kan


2 Answers

HTML and CSS3-only version (Fiddle):

HTML for group "D" (other groups are similar)

<div>
    <input type="radio" name="level0" value="D" id="D"/>
    <label for="D">D</label>
    <div class="sub1">
        <div>
            <input type="radio" name="level1" value="D0" id="D0"/>
            <label for="D0">D0</label>
        </div>
        <div>
            <input type="radio" name="level1" value="D1" id="D1"/>
            <label for="D1">D1</label>
            <div class="sub2">
                <div>
                    <input type="radio" name="level2" value="D10" id="D10"/>
                    <label for="D10">D1-0</label>
                </div>
                <div>
                    <input type="radio" name="level2" value="D11" id="D11"/>
                    <label for="D11">D1-1</label>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

.sub1, .sub2 { display: none; }

:checked ~ .sub1, :checked ~ .sub2 {
    display: block;
    margin-left: 40px;
}
like image 188
Ilya Streltsyn Avatar answered Jan 31 '23 11:01

Ilya Streltsyn


If you want more radio buttons to appear when a certain one is selected, I would suggest not "nesting" them inside one another in the html. Have javascript display a hidden group or RBs when a one is selected.

Frankly, I think using radio buttons to make a select box appear would be much more user friendly, as its clear that you're selecting from a different group. Too many radio buttons always looks ugly.

Other problems with your code: id's should be unique, put the RB text beside the radio button as opposed to inside the tag, and avoid table based layout if possible. inline javascript and css should be avoided too, but as this is a code sample it actually makes it more readable. Oh, most importantly, you have the other buttons set to appear on onclick, so they won't go away if you unselect the RB :D

like image 21
Gordon Gustafson Avatar answered Jan 31 '23 11:01

Gordon Gustafson