0

我有一些 javascript 应该验证一个复选框(使其成为强制性),但我的表单无论是否被选中,都只是提交,这是我的代码:

<script>
  function validateCheckBoxes(theForm) {
    if (!theForm.declare.checked) {
      alert ('You must tick the checkbox to confirm the declaration');
      return false;
    } else {    
      return true;
    }
  }
</script>

<form name="form" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateCheckBoxes(this);">
  <input type="checkbox" name="declare" id="declare">
  <input type="submit" name="submit" id="submit" value="submit">
</form>

关于它为什么不起作用的任何想法?

4

4 回答 4

1
<script type="text/javascript">
function validateCheckBoxes(theForm) 
{
if (!theForm.declare.checked)
{
    alert ('You must tick the checkbox to confirm the declaration');
    return false;
} else {    
    return true;
}
}
</script>

<form name="form" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateCheckBoxes(this);">

<input type="checkbox" name="declare" id="declare">

</form>

正如@shin 提到的,您需要在函数调用期间指定表单的对象。
theForm.declare.checked返回truefalse无需使用==运算符检查值。只需直接使用它(用户根据需要 - 否定结果)

于 2013-05-23T09:14:33.957 回答
0

改变你的函数调用

         return validateCheckBoxes(this);

例如:

      <form name="form" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateCheckBoxes(this);">

因为 theForm 应该引用一个对象

于 2013-05-23T09:07:41.707 回答
0
 <script>
  function validateCheckBoxes() 
  {
    if (document.getElementById('declare').checked == false)
     {
      alert ('You must tick the checkbox to confirm the declaration');
      return false;
     } else {    
     return true;
     }
  }
</script>

<form name="form" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi"        onsubmit="return validateCheckBoxes();">

<input type="checkbox" name="declare" id="declare" />
<input type="submit" name="submit" value="submit" />

</form>
于 2013-05-23T09:19:23.870 回答
0

这是我为我尝试和工作的

<script type='text/javascript'>
    function validateCheckBoxes() 
{
if (document.forms[0].declare.checked == false)
{
    alert ('You must tick the checkbox to confirm the declaration');
    return false;
} else {    
    return true;
}
}
</script>

<form name="form" method="POST" action="yourURL/search" id="eoi"  onsubmit="return validateCheckBoxes();">
    <input type="checkbox" name="declare" id="declare"/>
</form>

我认为您不需要将表单对象的引用传递给函数。

于 2013-05-23T09:42:08.733 回答