我有这个简单的HTML项目,用于验证空文本和radiobutton字段。如果其中一个字段为空,则显示错误,但错误消息仅在屏幕上闪烁一秒钟,然后再次消失。为什么会这样?
这是我的HTML代码
<form id="food_form">
<p>
<label>Your Name:
<input type="text" id="user_name" name="user_name">
</label>
<span id="error_user_name" class="error"></span>
</p>
<p>
Favorite Food?
<span id="error_radiobutton" class="error"></span><br>
<label><input type="radio" name="radiobutton" value="pizza">Pizza</label><br>
<label><input type="radio" name="radiobutton" value="burger">Burger</label><br>
<label><input type="radio" name="radiobutton" value="spaghetti">Spaghetti</label><br>
</p>
<input type="submit" value="Submit">
然后是我的Javascript代码
<script>
document.getElementById("food_form").onsubmit = validateForm;
function validateForm() {
var validName = validateTextBox("user_name", "error_user_name"),
validRadiobutton = validateRadioButton();
}
function validateTextBox(fieldId, errorId) {
var text = document.getElementById(fieldId).value,
errorSpan = document.getElementById(errorId);
if (text === "") {
errorSpan.innerHTML = "* please input your name";
}
}
function validateRadioButton() {
var radiobutton = document.getElementById("food_form").radiobutton,
errorSpan = document.getElementById("error_radiobutton"),
isChecked = false,
i;
errorSpan.innerHTML = "";
for (i = 0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick something.";
}
}
非常感谢您的回复。
答案 0 :(得分:1)
您的函数validateForm
设置了错误消息,但随后您再次调用validateRadioButton()
errorSpan.innerHTML = "";
。这就是“闪光”的原因
答案 1 :(得分:0)
您正在验证表单,但如果return false
事件的验证失败,您需要submit
。试试这个
function validateForm() {
var isTextBoxValid = validateTextBox("user_name", "error_user_name"),
isRadioButtonValid = validateRadioButton();
return isTextBoxValid || isRadioButtonValid;
}
function validateTextBox(fieldId, errorId) {
var text = document.getElementById(fieldId).value,
errorSpan = document.getElementById(errorId),
isValid = true;
if (text === "") {
errorSpan.innerHTML = "* please input your name";
isValid = false;
}
return isValid;
}
function validateRadioButton() {
var radiobutton = document.getElementById("food_form").radiobutton,
errorSpan = document.getElementById("error_radiobutton"),
isChecked = false, i,
errorSpan.innerHTML = "";
for (i = 0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
errorSpan.innerHTML = "* You must pick something.";
}
return isChecked;
}
在上面的代码中,我们为每个函数返回Boolean
值(true
/ false
),如果其中一个是true
我们正在提交表单
答案 2 :(得分:0)
尝试将提交按钮放在表单元素之外。
我一直有同样的问题,这对我有用。