[英]JavaScript Form validation doesn't stop the submit
我有一個包含一些復選框的表格:
<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);
該行return (false);
。 這就是為什么它不會阻止頁面提交。
您可以通過執行以下操作來修復錯誤:
theForm.land[0].focus();
由於land
是一個數組,所以才發生錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.