return false dos't禁止提交表格
return false doesn't prevent form submission
我有一个表单,我正在尝试对它进行一些验证,以获取旧浏览器和Safari上所需的字段(!)。到目前为止,我的解决方案似乎几乎有效。。。当我在Safari上提交带有空字段的表单时,会弹出错误,然后无论如何都会提交表单。我做错了什么?
我的表格是这样的:
<form id="primaryPostForm" method="POST" >
<input type="text" name="iName" id="iID" maxlength="25" required="required" value="" />
<textarea class="tipContent requiredAttr" name="taName" id="taID" maxlength="150" required="required" ></textarea>
<input type="hidden" name="submitted" id="submitted" value="true" />
<input id="submitBtn" type="submit" value="Submit">
我的验证如下:
function validate(){
$('#primaryPostForm').submit(function(){
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
alert("Please make sure the fields are filled in - thanks");
return false;}
})//end each
})//end submit
}
return false
仅从each
循环中退出。您需要存储一个可以从函数返回的结果:
function validate(){
$('#primaryPostForm').submit(function(){
var result = true;
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
alert("Please make sure the fields are filled in - thanks");
result = false;
return false; // exit loop
}
})//end each
return result;
})//end submit
}
首先,使用e.preventDefault();
而不是return false
。
要回答您的问题:return false
必须在提交事件回调的范围内:
function validate(){
$('#primaryPostForm').submit(function(e){
var ret = true;
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
alert("Please make sure the fields are filled in - thanks");
ret = false;
}
});
if(!ret){
e.preventDefault();
}
});
}
一个更简洁直接的方法是:
$('#primaryPostForm').submit(function(e){
var required = $(".requiredAttr", this).filter(function(){
return !this.value;
});
if(required.length){
alert("Please make sure the fields are filled in - thanks");
e.preventDefault();
}
});
试试这个,参考MDN
function validate(){
$('#primaryPostForm').submit(function(){
var result = [];
$("#primaryPostForm .requiredAttr").each(function(){
if($(this).val().length < 1){
result.push(false);
}
})//end each
result.some(function(element){return (element!=false)})
alert("Please make sure the fields are filled in - thanks");
})//end submit
}
相关文章:
- Javascript生成的表单未提交
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- HTML表单提交时未执行外部函数
- 在POST中将html表作为csv提交
- 我应该使用Ng提交还是点击表格
- 我想使用模态通过php文件发送邮件,并且我希望在提交关闭后关闭pop
- 提交后保留下拉选择的值
- 键入最后一位数字后自动提交
- 阻止表单元素提交
- JS表单提交"无法使用Chrome数据保护程序加载此页面.尝试重新加载页面.调试信息:POST CISmtuK
- 当所有输入文本字段都为空时,禁止表单提交,但当jquery中的任何字段不为空时允许提交
- 如何禁止html表单在提交时导航
- 在最后按钮之前禁止提交表单-避免编辑页面
- return false dos't禁止提交表格
- 如果存在 UI 错误,则禁止或提交记录 Netsuite Suitescript
- 如果此脚本禁止提交,为什么还要提交此表单
- 当按下Enter键时,禁止在html中提交表单
- 禁止提交空白输入和文本区域
- 禁止在提交表单后重新加载页面
- Jquery日期选择器-禁止在选择日期之前提交表单