Chris Gaines
Chris Gaines

Reputation: 3

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>

Upvotes: 0

Views: 50

Answers (2)

Steven Kuipers
Steven Kuipers

Reputation: 847

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;
}

Upvotes: 0

Jacob Gasser
Jacob Gasser

Reputation: 51

welcome to Stack Overflow!

To set the color of an element in JavaScript, you just need to access the element and then access the style object and then set the color value. Such as this

<p id="changeMe">Text will change to green :)</p>
    <script>
    // Using ES5 (Ecma-Script 2015) for compatibility sake
    var elementToChange = document.querySelector("#changeMe")
    elementToChange.style.color = "green"
    </script>

You can detect if a checkbox is checked in JavaScript like this,

<input type="checkbox" id="check">
<h1 style="color: red;" id="res">Checked?</h1>
<button onclick="isChecked()">Check If Checked</button>
<script>
  function isChecked() {
  var element = document.querySelector("#check")
  var res = document.querySelector("#res")
  if(element.checked) {
    res.style.color = "green"
  }
  else {
    res.style.color = "red"
  }
  }

</script>

Since we don't like to spoon feed here on Stack Overflow, I will let you put 2 and 2 together. Have a good day!

Upvotes: 2

Related Questions