[英]JavaScript: Why won't my form submit?
我的问题是我的表单<form name="enrollment" method="post" action="submit.php">
无法提交。 我的提交按钮如下所示: <input class="buttons" type="submit" name="submit" onclick="return validate()" value="Submit" />
。
它调用此JavaScript函数:
// Returns true if there are no errors and false if there are errors
function validate() {
// Something is not returning true here so that the form is not being submitted
if ( !window.err_exist ) {
// No errors
return true;
}
// There are errors
alert("Errors exist in the form!");
return false;
}
变量window.err_exist
在函数getReviewValues()
定义。 在getReviewValues()
,我设置window.err_exist = false;
。 然后,我使用表单的条件验证表单:
// Name
var r_string = "Name: ";
if ( document.forms["enrollment"]["name"].value.trim() == "" ) {
r_string += "<span class=\"error\">This is a required field!</span>";
window.err_exist = true;
} else {
r_string += document.forms["enrollment"]["name"].value;
}
然后,在getReviewValues()
的结尾,我return r_string;
动态反馈表单验证的状态。 也就是说,诸如"Name: This is a required field!"
。
现在,如果我填写表单,但将某些内容留空以便出现验证错误,则会收到警报"Errors exist in the form!"
并且表单未提交。 大! 但是,当我填写表格以确保没有验证错误时,我没有收到错误消息。 大! 但是,哦,不! 该表格仍未提交。 而且应该!
因此,由于我没有收到错误消息,因此执行路径必须在条件if ( !window.err_exist )
。 我看到了这一点,因为函数然后返回true
因此该函数永远不会发出消息。 但是,如果返回true
,那么我的表单应该提交。 因此它必须返回false
,因为表单未提交。 但是,如果返回false
,则执行路径不能处于假定的条件中。 如果真是这样,那么我会收到消息,但我未收到消息。 这是一个矛盾。
有人有想法么?
在表单元素上使用“ onsubmit”事件,而不是在提交按钮上使用“ onclick”处理程序。 例如:
<form onsubmit="return validate()">
此时,只要您的validate方法正确返回了true或false,它就应该按照您的期望进行操作。
请参阅http://www.w3schools.com/jsref/event_form_onsubmit.asp以获得更好的参考。
验证成功后(window.err_exist!= false),脚本将返回true。 因此,您为点击事件而不是提交返回true。
这可以通过执行jeltine所说的<form onsubmit="validate()">
来解决,也可以通过替换
<input class="buttons" type="submit" name="submit" onclick="return validate()" value="Submit" />
与
<input class="buttons" type="button" name="submit" onclick="validate()" value="Submit" />
然后更改validate函数以调用form.submit();
没有错误。
例:
//must add id to get element by id
<form name="enrollment" id="enrollment" method="post" action="submit.php">
function validate() {
// Something is not returning true here so that the form is not being submitted
if ( !window.err_exist ) {
// call submit on form
var myform = document.getElementById("enrollment");
myform.submit();
}
// There are errors
alert("Errors exist in the form!");
return false;
}
这样做的好处是,您可以根据需要对更改表单参数(如操作或方法)进行更多控制。 如果不需要这些,则只需更改为onsubmit=""
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.