0

I am having difficulty getting JavaScript to

  1. validate one radio button is selected and
  2. validating at least one checkbox is selected.

My current code follows:

<body>
  <script type="text/javascript">
  if((document.form1.gender[0].checked===false) &&(document.form1.gender[1].checked===false))
  {  
    alert("You must make a choice");
  }
  function isOneChecked() {
    var chx = document.getElementsByTagName("input");
    for (i=0; i<chx.length; i+++++) {
      if (chx[i].type == "radio" && chx[i].checked) {
        return true;
      }
    }
    alert("You must select at least one");
  }
  </script>

  <p>
    <input type="radio" name="gender" value="male"> Male
    <input type="radio" name="gender" value="female"> Female
  </p>
  <p>Select all sport interests that apply.</p>
  <input type="checkbox" name="chkSport" value="football" />Football<br />
  <input type="checkbox" name="chkSport" value="baseball" />Baseball<br />
  <input type="checkbox" name="chkSport" value="basketball" />Basketball<br />
  <input type="checkbox" name="chkSport" value="soccer" />Soccer<br />
  <input type="checkbox" name="chkSport" value="trackandfield" />Track and Field<br />
  <input type="checkbox" name="chkSport" value="none" />None<br />
rfornal
  • 5,072
  • 5
  • 30
  • 42
  • Welcome to Stack Overflow! Please go through answers on linked question. The problem is that the JS code is executed before the HTML elements are available in the DOM. Ping me if you face any problems. – Tushar Nov 25 '16 at 03:46
  • where you need this? on button click? can I suggest jquery? obviously this will shoot error in your code `for (i=0; i – Santhucool Nov 25 '16 at 04:04

0 Answers0