Search code examples
htmlcssradio-button

Check text color when radio is checked


I'm trying to change the text color for p1 when a radio button is selected. if up is selected, green, or down, red. I can change the color of the radio boxes using css without any problems but I can't get the text to change.

<form>
  <p1>Test1: </p1>
  <input type="radio" id="up" style="vertical-align: middle" name="test1" value="Up" checked> Up
  <input type="radio" id="down" style="vertical-align: middle" name="test1" value="Down"> Down
  <input type="radio" id="route" style="vertical-align: middle" name="test1" value="en route"> En route  
  <input type="radio" id="house" style="vertical-align: middle" name="test1" value="In-House"> In-House  
  <b>  Notes: </b><br>
 </form>


Solution

  • If you are looking for a pure CSS solution, because you didn't tag it as a js question, you can also do that but you have to shuffle your HTML around a bit. You can add any number of radio inputs and this will still work as long as the p element comes after them.

    <form>
      <input type="radio" id="up" style="vertical-align: middle" name="test1" value="Up" checked><label for="up"> Up</label>  
      <input type="radio" id="down" style="vertical-align: middle" name="test1" value="Down"><label for="down"> Down</label>
      <p class="color-me">Test1: </p>
     </form>
    
    form {
      display: flex;
      flex-direction: row;
    } 
    
    .color-me {
      order: 1;
    }
    
    #up, #up ~ label, #down, #down ~ label {
      order: 2;
    }
    
    
    #up:checked ~ .color-me{
      background-color: tomato;
    }
    
     #down:checked ~ .color-me{
       background-color: steelblue;
    }