简体   繁体   English

javascript 验证表单中的单选按钮

[英]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.该代码旨在验证一个单选按钮是否被选中,否则返回 false 到当前页面,否则继续执行表单操作。 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:这是循环完成要检查的re值:

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

return true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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