我试图阻止我的表单在确认消息取消时提交,但如何从each()
内取消我的表单提交?
$('#myForm').submit(function() {
var inputs = $(this).find('input:checked');
inputs.each(function() {
var inputId = $(this).attr('id');
if(inputId != undefined && inputId.substring(0, 8) == 'inputName') {
var r = confirm("Are you sure you want to continue?");
if (r == true) {
return true;
} else {
// This doesn't stop the form submit
return false;
}
}
});
return true;
});
答案 0 :(得分:1)
您可以使用传递给事件侦听器的事件参数;它有a method named preventDefault()
,可以停止执行默认操作。
$('#myForm').submit(function (e) {
var inputs = $(this).find('input:checked');
inputs.each(function () {
var inputId = this.id;
if (inputId != undefined && inputId.substring(0, 8) == 'inputName') {
var r = confirm("Are you sure you want to continue?");
if (!r) {
e.preventDefault();
}
}
});
});