简体   繁体   English

JavaScript表单验证不会停止提交

[英]JavaScript Form validation doesn't stop the submit

I have a form which includes some checkboxes: 我有一个包含一些复选框的表格:

<form class="lightblue" action="someValidRef" method="post" onsubmit="return client_validation(this)">
...
<div>
      <label>Label</label>
      <ul>
        <li><input type="checkbox" name="land" value="Austria">Austria</li>
        <li><input type="checkbox" name="land" value="Belgium">Belgium</li>
        <li><input type="checkbox" name="land" value="Bulgaria">Bulgaria</li>
        <li><input type="checkbox" name="land" value="Czech Republic">Czech Republic</li>
        <li><input type="checkbox" name="land" value="Switzerland">Switzerland</li>
        <li><input type="checkbox" name="land" value="Germany">Germany</li>
        <li><input type="checkbox" name="land" value="Denmark">Denmark</li>
        <li><input type="checkbox" name="land" value="Spain">Spain</li>
        <li><input type="checkbox" name="land" value="Estland">Estland</li>
    </ul>
</div>
...
<div>
        <input type="submit" name="submit" value="send" />
        <input type="reset" name="reset" value="reset" />
</div>

with following JS: 使用以下JS:

<script language="JavaScript1.2">
function client_validation(theForm)
{
    ...
    var land = theForm.land;
    var land_set = false;
    for (i = 0; i < land.length; i++) {
      if (land[i].checked) {
        land_set = true;
      }
    }
    if(!land_set){
        alert("please choose a country");
        theForm.land.focus();
        return (false);
    }   
    ...
  return true;
}
</script>

I omitted other form fields and other validation parts for this post. 在此,我省略了其他表单字段和其他验证部分。 Every other part of the validation is working, but this list of checkboxes counteracts every validation. 验证的每个其他部分都可以正常工作,但是此复选框列表抵消了每个验证。 While a country is selected, it works fine and other validations are executed as well. 选择一个国家/地区后,它可以正常运行,并且还执行其他验证。 But as soon as I click on submit while no country is selected, my form still submits . 但是,当我在没有选择任何国家的情况下单击提交时,我的表格仍会提交 It even gives me the alert saying "please choose a country", but upon closing this message, the form is submitted... Why is it still submitting? 它甚至使我警惕地说“请选择一个国家”,但是在关闭此消息后,表单已提交...为什么仍在提交? I tried changing the "return true" statement in the end of the validation to return land_set , but it's not working either. 我尝试在验证结束时将“ return true”语句更改为return land_set ,但它也不起作用。

 theForm.land.focus();

The above line of code in your function is throwing an error and control never gets to the line return (false); 函数中的上述代码行引发了错误,并且控件从不return (false);该行return (false); . That's why it is not preventing the page submit. 这就是为什么它不会阻止页面提交。

You can fix the error by doing this: 您可以通过执行以下操作来修复错误:

theForm.land[0].focus();

Since land is an array, that's why the error was occurring. 由于land是一个数组,所以才发生错误。

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

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