yaksushi yaksushi - 26 days ago 16
HTML Question

Javascript form validation checkbox and radio not working

I have a form that I need to validate with javascript to make sure at least one checkbox and one radio is checked. I know it would probably be easier to use jQuery but I'm trying to accomplish this with pure javascript. Here is the code:

<form name="bulbform" action="compute.php" onsubmit=" return validateForm()" method="post">
<p>Enter your name: <input type="text" name="name" size="20"></p>
<p><strong>Light Bulbs</strong></p>
<label><input type="checkbox" name="bulbs[]" value="2.39">Four 25-watt light bulbs for $2.39</label><br>
<label><input type="checkbox" name="bulbs[]" value="4.29">Eight 25-watt light bulbs for $4.29</label><br>
<label><input type="checkbox" name="bulbs[]" value="3.95">Four 25-watt long-life light bulbs $3.95</label><br>
<label><input type="checkbox" name="bulbs[]" value="7.49">Eight 25-watt long-life light bulbs $7.45</label><br>
<p><strong>Payment Method</strong></p>
<label><input type="radio" name="cc" value="Visa">Visa</label><br>
<label><input type="radio" name="cc" value="Master Card">Master Card</label><br>
<label><input type="radio" name="cc" value="Discover">Discover</label><br>
<p><input type="submit" value="Order" /> <input type="reset" value="Clear form"/></p></form>


Here is my javascript

var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === 'radio' && radios[i].checked) {
// get value, set checked flag or do whatever you need to
value = radios[i].value;
alert(value);
return true;
}
else{
alert("You must select a payment method.")
return false;
}


With the else removed I'm able to show the credit card selected but when I add the else it always says you must select a payment method and is never true... Thanks ahead of time for any advice you can give.

Answer

See this plunker: https://plnkr.co/edit/5NiIA1w9axvmOJEjXVlP

function validateForm() {

  var radios = document.getElementsByTagName('input');
  var value;
  var paymentMethodSelected = false;

  for (var i = 0; i < radios.length; i++) {

    if (radios[i].type === 'radio' && radios[i].checked) {
      // get value, set checked flag or do whatever you need to
      value = radios[i].value;
      alert(value);
      paymentMethodSelected = true;
    }

  }

  if (!paymentMethodSelected) {
    alert("You must select a payment method.");
    return false;
  }

  return true;

}
  • You don't have an ending form tag (not critical, but good practice)
  • You were returning from the validation function before you had checked all radio buttons
  • The check for an invalid form state should be handled outside the for loop
Comments