Radio button show/hide content

12,702

Place label tags after both in the input tags. Like below

<input type=radio id="show" name="group">
<input checked type=radio id="hide" name="group">
<label id="id1" for="show"><span id="id1">show</span></label>
<label id="id2" for="hide"><span id="id2">hide</span></label> 
<span id="content">Content</span>

Add these css rules to existing rules

input#show:checked ~ label#id1{
  display:none;
}
input#show:checked ~ label#id2{
   display:block;
}

input#hide:checked ~ label#id2{
   display:none;
}
input#hide:checked ~ label#id1{
   display:block;
}

demo http://jsfiddle.net/vtfqW/1/

Share:
12,702
user3096206
Author by

user3096206

Updated on June 15, 2022

Comments

  • user3096206
    user3096206 almost 2 years

    I am trying to achieve a show/hide result without javascript and just the radio button.

    I've managed to get to this part:

    <label for="show"><span>show</span></label>
    <input type=radio id="show" name="group">
    <label for="hide"><span>hide</span></label>    
    <input type=radio id="hide" name="group">
    <span id="content">Content</span>
    
    
    input {
        display:none;
    }
    
    span#content {
        display:none;
    }
    input#show:checked ~ span#content {
      display:block;
    }
    
    input#hide:checked ~ span#content {
        display:none;
    }
    

    Demo: http://jsfiddle.net/vtfqW/

    What I am trying to do now is to hide each time the "Show" and "Hide" buttons when they are active. So it will need to start with hidden content and just has the "Show" button and when you click it show the content, hide the "Show" button and show you the "Hide" button.

    Is this possible without Javascript?

    Thank you!

  • user3096206
    user3096206 over 10 years
    Although it looks good, does it load by showing everything or is it just me?
  • user3096206
    user3096206 over 10 years
    Made 1 tiny change and it now works awesomely! Thank you very much!
  • hemanth
    hemanth over 10 years
    it loads by showing everything. If you just want "show" to be displayed initially, add "checked" attribute to hide radio input.
  • sc28
    sc28 over 6 years
    Thanks for this useful solution. However in my case I need the radio <input>s to be inside a <fieldset>, and for some reason the CSS doesn't work anymore. Any ideas why, and how to make it work also if the <input>s are in a <fieldset>?
  • sc28
    sc28 over 6 years
    Update: I found out that it works if the span is inside the fieldset too, but not outside. Any way to make it work outside too? Cf. Fiddle