I'm a Noob, who can't figure out how to fix my broken javascript validation for my form. I believe the problem is with my selector (identified by the Not Working Comment), but don't know javascript well enough to know how to fix it. I'm trying to make a form with several different types of input, and validate each. My syntax works fine for regular text inputs and drop down menus, but not for radio. Simple answers (that I can understand) are preferred to complex answers (that I can't).

I've looked at this issue a bunch on here, and don't want to validate each radio button individually, i.e. if choice = 1.. if choice = 2.. if choice = 99, just that 1 of the buttons has been selected. I'm not sure whether a for loop is required for this, or if there is a way to do it that is similar to my existing code that works for the other inputs.

document.querySelector('form').onsubmit = function() {
  if (!document.querySelector('select[name=country]').value) {
    alert('You must choose a country');
    return false;
  }

  // <!--NOT WORKING PART-->    
  else if (!document.querySelector('custom-control-input[type=radio]:checked').value) {
    alert('You must select a gender');
    return false;
  }
  return true;
};
<div class="form-group">
  <select name="country">

    <option disabled selected value="">Country</option>
    <option value="Canada">Canada</option>
    </option>
    <option value="USA">USA</option>
    </option>
  </select>
</div>

<div class="custom-control custom-radio">
  <input type="radio" name="customRadio" id="customRadio1" class="custom-control-input">
  <label class="custom-control-label" for="customRadio1">Male</label>
</div>

<div class="custom-control custom-radio">
  <input type="radio" name="customRadio" id="customRadio1" class="custom-control-input">
  <label class="custom-control-label" for="customRadio1">Female</label>
</div>

2 Answers

1
MaxO On Best Solutions

Your arguments in the query selector are wrong.

This worked for me:

else if (!document.querySelector('[type=radio]').checked) {
    alert('You must select a gender');
    return false;
}

-1
Sarmad Ali On

One method that you tell already by selecting every single element by id and the other the following

 function checkRadioButton() {
    return ($('input[type=radio]:checked').size() > 0);
}

It will check the whole page and return a single checked redio button if it is.