Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading