[英]javascript checkbox validation
復選框的驗證無效。 它沒有任何錯誤。 你能幫我解決嗎? 以及如何將錯誤合並在一個警報中而不是一個接一個地處理?
謝謝你的幫助。
HTML代碼:
<form class="contact_form" action="" method="post" name="contact_form" onsubmit="returnonFormSubmit(this)">
<li>
<label for="First Name">First Name:</label>
<input type="text" name="visitor_name" /><br />
</li>
<li>
<label for="condition">I agree with the terms and conditions.</label>
<input type="checkbox" name="lan" /><br />
</li>
<li>
<label for="Male">Male:</label>
<input type="radio" name="gender" value="m" /> Female:<input type="radio" name="gender" value="f" /><br />
</li>
<li>
<label for="National Rating">National Rating:</label>
<select name="make">
<option selected>-- SELECT --</option>
<option> Below 1200 </option>
<option> 1200 - 1500 </option>
<option> 1500 - 1800 </option>
<option> 1800 - 2100 </option>
<option> Above 2100 </option>
</select><br />
</li>
<li>
<button class="submit" type="submit">Submit</button>
</li>
<div id="error_message" style="color:#ff0000;"></div>
JavaScript代碼:
function onFormSubmit(form_element)
{
var checked = 0;
var letters = /^[a-zA-Z]+$/;
if (form_element.visitor_name.value.match(letters))
{
true;
}
else
{
alert("Please enter a valid first name. For example; John.");
false;
}
if (form_element.lan.checked == false)
{
alert("Please accept the terms and conditions");
false;
}
if (form_element.gender[0].checked == false && form_element.gender[1].checked == false)
{
alert("Please select a gender.");
false;
}
if (form_element.make.selectedIndex == 0)
{
alert("Please select your rating interval.");
form_element.make.focus();
false;
}
return true;
}
您在onsubmit="returnonFormSubmit(this)"
有錯字。 它應該是
onsubmit="return onFormSubmit(this)"
在控制台打開的情況下運行它會給您帶來寶貴的錯誤/警告。 嘗試使用Chrome的開發人員工具,Firefox的Firebug或類似工具。
要將錯誤合並為一個,可以從一個空字符串msg = ''
,然后在出現錯誤時附加到該字符串。 然后在函數底部, alert(msg)
並返回false(如果它不是空值),否則返回true。
您應該將錯誤消息連接到變量中。
function onFormSubmit(form_element)
{
var checked = 0;
var letters = /^[a-zA-Z]+$/;
var errorMessage = "";
if (!form_element.visitor_name.value.match(letters))
{
errorMessage += "Please enter a valid first name. For example; John.\n";
}
if (form_element.lan.checked == false)
{
errorMessage += "Please accept the terms and conditions\n";
}
if (errorMessage != "")
{
alert(errorMessage);
return false;
}
return true;
}
在returnonFormSubmit(this)中修復錯字后,它可以在Chrome和Firefox中使用。
(順便說一句:你忘記了回報)
為了合並警報,我將使用數組。 例:
function onFormSubmit(form_element)
{
var checked = 0;
var letters = /^[a-zA-Z]+$/;
var alerts = new Array();
if (!form_element.visitor_name.value.match(letters))
alerts.push("Please enter a valid first name. For example; John.");
if (!form_element.lan.checked)
alerts.push("Please accept the terms and conditions");
if (alerts.length == 0) {
return true;
}
alert(alerts.join("\n"));
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.