表单中单选按钮的javascript验证

时间:2013-02-17 01:59:12

标签: javascript forms form-submit radio onsubmit

希望有人能够了解以下代码,该代码始终警告下面的错误。代码被设计为验证一个单选按钮被选中,否则返回false到当前页面,否则继续进行表单操作。提前感谢你!!

  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;

  }
 };

表格如下:

  <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>

&LT;

1 个答案:

答案 0 :(得分:0)

在循环结束后,您想要检查re的值:

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

return true;