Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

James Barrett
James Barrett
13,253 Points

Radio button JavaScript validation bug

Hi there,

I am in the process of implementing some JavaScript validation to my contact form. When I press submit with a radio button checked, my custom error message still appears. Here is my code:

JavaScript:

            function validate() {
            var error = 0;

            var errorgender = document.getElementById("errorgender");
            var user_gender = document.register.user_gender;
            for (var i in user_gender) {
              if(!user_gender[i].checked) {
                errorgender.style.visibility = "visible";
                error = 1;
              } else {
                 errorgender.style.visibility = "hidden";
              }   
            }
         }

        if (error == 0) {
                return true;
            } else {
                return false;
            }

HTML:

    <label for="gender">Gender</label>
                  <input type="radio" id="male" name="user_gender" value="male"     required>Male<br>
                  <input type="radio" id="female" name="user_gender" value="female"     required>Female<br>
                  <input type="radio" id="other" name="user_gender" value="other"     required>Other<br>
                  <span id="errorgender" class="error">Gender Is Required</span>

    <button type="submit" value="Submit" onclick="return validate();">Register</button>

CSS:

    .error {
        color: red;
        font-style: italic;
        font-size: 17px;
        visibility: hidden;
    }

I should also note that all other JavaScript validation for other fields such as firstname, lastname, etc. are all working fine; so I am assuming that the problem does not lay elsewhere.

Any suggestions?

Thanks a lot, James.

1 Answer

David Bath
David Bath
25,940 Points

Two of the options are always going to be unchecked, so the way you are checking now the error variable will always be 1. I would suggest initializing "error" to 1, and then if one of the options is selected then set it to 0. Then in the "if error == 0" block you can set the visibility of the error text.