复选框验证无效

时间:2013-05-23 09:03:53

标签: javascript function validation

我有一些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 个答案:

答案 0 :(得分: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,无需使用==运算符检查值。只需直接使用它(用户,具体取决于需要 - 否定结果)

答案 1 :(得分:0)

更改您的函数调用,如

         return validateCheckBoxes(this);

<强>例如

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

因为theForm应该引用一个对象

答案 2 :(得分: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>

答案 3 :(得分: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>

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

相关问题