我在JavaScript中做错了什么?如果用户忘记输入任何HTML表单字段,我想显示错误消息。我想为名称,电子邮件和电话号码字段创建一条错误消息。即使用户输入了他们的名字,我也希望余数为2或余数为1的错误消息,或者没有错误消息。我在下面附上了我的JavaScript代码。感谢那些帮助的人。
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
if (name == "") {
document.getElementById('error').innerHTML = "Please enter your name";
ret = false;
}
var email = document.forms["contactform"]["email"].value;
if (email == "") {
document.getElementById('erroremail').innerHTML = "Please enter your email";
ret = false;
}
var phone = document.forms["contactform"]["phone"].value;
if (phone == "") {
document.getElementById('errorphone').innerHTML = "Please enter your phone";
ret = false;
}
return ret;
}
答案 0 :(得分:0)
创建一个名为:
的变量var fieldsInError = "";
然后在每次检查的验证中,如果验证失败,请添加字段:
fieldsInError += "name," (or whatever the field is)
然后在函数结束时更新您的错误字段,例如:
document.getElementById('error').innerHTML = "Please enter " + fieldsInError.substring(0, fieldsInError.length-1);
所以你的功能看起来像这样:
function validateForm() {
var fieldsInError = "";
var name = document.forms["contactform"]["name"].value;
if (name == "") {
fieldsInError += "name,"
}
var email = document.forms["contactform"]["email"].value;
if (email == "") {
fieldsInError += "email,"
}
var phone = document.forms["contactform"]["phone"].value;
if (phone == "") {
fieldsInError += "phone,"
}
if(fieldsInError != ""){
document.getElementById('error').innerHTML = "Please enter " + fieldsInError.substring(0, fieldsInError.length-1);
return false;
} else {
return true;
}
}
答案 1 :(得分:0)
如果您希望为每个输入单独显示错误,则只需添加else
空innerHTML
。
这样的事情:
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
} else {
nameError.innerHTML = "";
}
此处的完整示例:https://jsfiddle.net/1h1tkh7y/