我有一个使用 Ajax 提交的表单。
如果选中复选框(接收最新报价等),如果未填写字段,我想阻止提交表单。
如果没有选中该复选框,那么我不在乎字段是否填写,即使为空也可以提交表单。
我当前遇到的问题是,即使选中了复选框且字段为空,表单仍在提交。
我尝试了return false
、event.stopImmediatePropagation()
、event.stopPropagation()
和event.preventDefault();
。它们都不会阻止表单提交。
function check()
附加到提交按钮。
欢迎任何和所有建议。
如果我可以提供任何其他信息,请告诉我。
谢谢
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
return false; //event.preventDefault()//etc etc
}
if (!email.validity.valid) {
showEmailError();
return false; //event.preventDefault()//etc etc
}
};
};
setTimeout(function() {
document.getElementById("allow").addEventListener("click", sendAjax);
}, 1);
<button id="allow" onclick="check()">
<span id="a"></span>
</button>
最佳答案
按照 chandan 的建议,我编辑了 function check()
并且它有效。
RollingHogs 答案也应该有效,但我使用的按钮不是提交类型,因为在提交表单之前需要运行其他一些 ajax 函数,所以我不能接受。
无论如何,这是完成这项工作的代码:
function check (event) {
if (adverts.checked === true){
// if the email field is valid, we let the form submit
if(!fname.validity.valid && !email.validity.valid){
showNameError();
showEmailError();
}else if (!fname.validity.valid) {
// If it isn't, we display an appropriate error message
showNameError();
}else if(!email.validity.valid) {
showEmailError();
}else{
sendAjax();
}
}else{
sendAjax();
};
};
关于javascript - 停止提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60669590/