我有一个简单的联系表格,上面有姓名,电子邮件,电话号码和短信。 我用javascript来验证它并提供反馈。所有其他功能都可以正常工作,如果输入框包含无效字符或值,则将输入框变为红色。但是,当我对所有框执行状态检查时,即使只有一个输入中有一个值,表单也会提交。
这是我的jS ......
function submit_it() {
var name = document.getElementById("username");
var email = document.getElementById("email");
var num = document.getElementById("racenum");
var messagecontent = document.getElementById("messagecontent");
var inputs = [];
inputs[0] = name;
inputs[1] = email;
inputs[2] = num;
inputs[3] = messagecontent;
for(i = 0; i < inputs.length; i++) // Loop through input elements.
{
// Perform presence check.
if(inputs[i].value=="" || messagecontent.value == 'null') //If check fails
{
alert("There are errors in your message form."); // Error
name.focus(); // Return cursor to first input element.
break;
return;
}
else // If Presence check passes
{
$.post("sndmsg.php", { com: "" , pg: ""});
alert("Your message has been sent.");
for(i = 0; i < inputs.length; i++)
{
inputs[i].value = '';
inputs[i].style.backgroundColor = '#fff';
}
break;
console.log(logit);
return;
}
}
}
我假设它是循环或If语句的问题,但我无法弄清楚为什么它没有收到错误! 任何帮助将不胜感激!
答案 0 :(得分:0)
使用它:
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
并在您的代码中执行此操作:
var val = inputs[i].value;
if(val.trim() == "" || messagecontent.value == 'null'){// stuff}
答案 1 :(得分:0)
你的循环存在缺陷。您实际上是尝试为每个正确填充的字段POST一次表单。此外,您将永远不会到达return语句,因为break语句将在此时退出for循环。
你应该在for循环完成之后移动POST电话,并确保只有在所有字段都正确填充的情况下才调用它。像这样构造的东西(伪代码):
for...
{
if field check fails
{
alert, highlight whetever
return; // return from whole function
}
}
// we come here only if all fields checked ok
post data