简体   繁体   中英

javascript validation of radio buttons in a form

hope someone can shed light on the below code which alerts always the error below. The code was devised to validate one radio button is selected otherwise return false to the current page otherwise proceed with the form action. Thanking in you in advance

  function onDisplayItemsForm(){
  var re = false;           // used to determine when a button is checked
  var radIdSelected = frmDisplayItems; 

// traverse the radio buttons
// if one is checked sets re to true, and stops the iteration
    for(var i=0; i<radIdSelected.length; i++) 
    {
      if(radIdSelected[i].checked == true) 
      {
       re = true;
   break;

       }

   if (!radIdSelected[i].checked) 
{
      alert("Please select product");
      return false;
    }
     return true;

  }
 };

The form is as follows:

  <form name="frmDisplayItems" action="showItem.php" onsubmit="return onDisplayItemsForm();" >


      <table width="50%" border="1">

  <th>Country of Origin</th>
  <th>Select</th>
  </tr>


         <td><input name=\"radId\" type=\"radio\" value=\"$id\" /></td>



  </tbody>
  </table>

  <p><input name="btnSubmit" type="submit" value="Select"/>  </p>
  </form>

<

It's the value of re that you want to check after the loop has finished:

if (!re)
{
    alert("Please select product");
    return false;
}

return true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM