gpt4 book ai didi

JavaScript 表单验证不会停止提交

转载 作者:行者123 更新时间:2023-12-02 14:05:01 24 4
gpt4 key购买 nike

我有一个包含一些复选框的表单:

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

使用以下 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>

我在这篇文章中省略了其他表单字段和其他验证部分。验证的所有其他部分都在工作,但是此复选框列表会抵消每个验证。选择国家/地区后,它可以正常工作,并且还会执行其他验证。但是,当我在未选择任何国家/地区的情况下单击“提交”时,我的表单仍然会提交。它甚至给我一个警告,说“请选择一个国家/地区”,但关闭此消息后,表单已提交...为什么它仍在提交?我尝试将验证结束时的“return true”语句更改为 return land_set,但它也不起作用。

最佳答案

 theForm.land.focus();

函数中的上述代码行抛出错误,并且控制永远不会到达行return (false);。这就是为什么它不会阻止页面提交。

您可以通过执行以下操作来修复错误:

theForm.land[0].focus();

由于 land 是一个数组,这就是发生错误的原因。

关于JavaScript 表单验证不会停止提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40128882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com