我有一个使用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>
答案 0 :(得分:0)
我想问题是您阻止了button.onclick
的传播,而不是form.onsubmit
。尝试将check()
从onclick移至onsubmit:
<form id="fname" ... onsubmit="check(event)">
<button id="allow" type="submit"></button>
</form>
功能check()
应该可以正常运行,而无需进行任何编辑。
此外,请参见this question
中的代码更新:编辑时间过长,已经回答。请在原始答案发布为答案后尽快删除它。
答案 1 :(得分:0)
正如chandan所建议的那样,我编辑了function check()
,它可以正常工作。
RollingHogs答案也应该有效,但是我使用的按钮不是类型Submit,因为在提交表单之前还需要运行其他一些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();
};
};