Search code examples
javascriptradio-buttongetelementbyid

How to apply Condition on specific Radio Button using JavaScript


What I want is when I click on specific red id Radio Button then it shows me Alert as you can see in the code... in my case its not happening.. what is the issue and how can I sort this?

<form>
  What color do you prefer?<br>
  <input type="radio" name="colors" id="red">Red<br>
  <input type="radio" name="colors" id="blue">Blue
</form>
<script>
  if (document.getElementById("red").checked == true) {
    alert('working');
  }
</script>


Solution

  • You need an eventListener

    document.getElementById("red").addEventListener("change", myAlert); 
    
    function myAlert() {
        alert('working');
    }
    <form>
        What color do you prefer?<br>
        <input type="radio" name="colors" id="red">Red<br>
        <input type="radio" name="colors" id="blue">Blue
    </form>