我正在尝试让Safari验证我的表单并停止提交,如果没有填写必填字段。我目前有以下提交功能。
$('#qtrAuditform').on('submit', function(event) {
event.preventDefault();
var uagent = navigator.userAgent.toLowerCase();
if (/safari/.test(uagent) && !/chrome/.test(uagent)) {
//If required attribute is not supported or browser is Safari (Safari thinks that it has this attribute, but it does not work), then check all fields that has required attribute
$("#qtrAuditform [required]").each(function(index) {
if (!$(this).val()) {
//If at least one required value is empty, then ask to fill all required fields.
alert("Please fill all required fields.");
event.preventDefault();
return false;
}
});
}
var $form = $(this),
data = $form.serialize();
var url = 'http://localhost:8888/datatest';
$.ajax({
type: 'POST',
url: url,
data: data,
success: function() {
alert('Your form has been successfully submitted!');
},
fail: function() {
alert('something went wrong...try again');
}
});
});
我收到提醒请填写必填字段,但在我收到表单提交的提醒后立即收到。如何在仍然填写需要填写的字段的同时不提交表单?
答案 0 :(得分:1)
整个事件应该立即返回false。
$('#qtrAuditform').on('submit', function(event) {
event.preventDefault();
var uagent = navigator.userAgent.toLowerCase();
if (/safari/.test(uagent) && !/chrome/.test(uagent)) {
//If required attribute is not supported or browser is Safari (Safari thinks that it has this attribute, but it does not work), then check all fields that has required attribute
$("#qtrAuditform [required]").each(function(index) {
if (!$(this).val()) {
//If at least one required value is empty, then ask to fill all required fields.
alert("Please fill all required fields.");
event.preventDefault();
return false;
}
});
}
var $form = $(this),
data = $form.serialize();
var url = 'http://localhost:8888/datatest';
$.ajax({
type: 'POST',
url: url,
data: data,
success: function() {
alert('Your form has been successfully submitted!');
},
fail: function() {
alert('something went wrong...try again');
}
});
//Return false immediately
return false;
});
我希望这会有所帮助。
答案 1 :(得分:-2)
这就是我现在所拥有的,这是有效的。
$('#qtrAuditform').on('submit',function(event){
//event.preventDefault();
var uagent = navigator.userAgent.toLowerCase();
if(/safari/.test(uagent) && !/chrome/.test(uagent)) {
//If required attribute is not supported or browser is Safari (Safari thinks that it has this attribute, but it does not work), then check all fields that has required attribute
$("#qtrAuditform [required]").each(function(index) {
if (!$(this).val()) {
//If at least one required value is empty, then ask to fill all required fields.
alert("Please fill all required fields.");
//event.preventDefault();
return false;
}
});
return false;
}
var $form = $(this),
data = $form.serialize();
var url = 'http://localhost:8888/datatest';
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(){
//window.location = "http://www.google.com";
alert('Your form has been successfully submitted!');
},
fail:function(){
alert('something went wrong...try again');
}
});
return false;
});

唯一不能正确执行的操作是返回表单已在Safari中正确提交的警报。它确实在其他浏览器中返回该警报。