Search code examples
javascripthtmlcolors

How do I validate a radio button with JavaScript?


How do I validate a radio button? I want to make it so that if the user left the radio button unclicked the section background will turn a red colour/color.

Here is the HTML Page

<p id="caption_project">Project Selection
    <br/>
    <input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
    <label for="in_restaurant">LEGO Project</label>
    <br/>

    <input type="radio" name="f__project" id="in_humber" value="Humber News"/>
    <label for="in_humber">Humber Current Project</label>
                        <br/>

    <input type="radio" name="f__project" id="in_self" value="self-determined"/>
    <label for="in_self">Self-determined Project</label>
</p>

So how do I turn the background red when they leave it unchecked?


Solution

  • You need to think of some event the user will fire which you want to trigger the function that makes the background go red. That could be if the user clicks on the next form control. Then when that event fires you test whether they checked any radio buttons. If they did not (!checked) then you set the style attribute of your p element to background:red:

    const nextThing = document.querySelector('#next-thing');
    
    const p = document.querySelector('p');
    
    nextThing.addEventListener('click', function(){
      const checked = document.querySelector("input[name='f__project']:checked");
      if(!checked){
        p.setAttribute('style', 'background:red');
      }
    });
    <p id="caption_project">Project Selection
      <br/>
      <input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
      <label for="in_restaurant">LEGO Project</label>
      <br/>
      <input type="radio" name="f__project" id="in_humber" value="Humber News"/>
      <label for="in_humber">Humber Current Project</label>
      <br/>
      <input type="radio" name="f__project" id="in_self" value="self-determined"/>
      <label for="in_self">Self-determined Project</label>
    </p>
    
    <button id='next-thing'>Next form control</button>