开发者问题收集

Jquery:无法使 .preventDefault 工作

2013-04-03
957

单击“提交”按钮时,我尝试捕获提交并快速执行 AJAX 请求,以查看表单中指定的时间和日期的预订是否已存在。如果是,则停止表单提交并提醒用户该日期和时间的预订已存在!如果没有预订,请继续提交表单。就我而言,我无法让 .preventDefault 工作,除非我将其放在提交函数的末尾。任何想法和指示都非常感谢,我已经被困在这个问题上三个小时了,而且似乎没有任何进展。我 99% 确定我只是个白痴,所以提前道歉!

这是我的代码:

$('#formID').submit(function(event){

            var InspectionDate = $('#datepicker').val().split('/');
            InspectionDate.reverse();
            InspectionDate = InspectionDate.join('-');
            InspectionHour = $('#time_hour').val();
            InspectionMinutes = $('#time_minutes').val();
            var InspectionDateTime = InspectionDate + ' ' + InspectionHour + ':' + InspectionMinutes + ':00';
            $.ajax({
               type: "POST",
               url: "ajax_booking_check.php",
               data: 'InspectionDateTime='+ InspectionDateTime,
               cache: false,
               success: function(response){
                if(response = 1){
                alert("An appointment for the selected Date and Time already exists.\n\nDouble Bookings are not possible.\n\nPlease refer to the calender to find an available appointment.");
                event.preventDefault();
                }
                else{
                //submit form   
                }
               }
            });
        });
2个回答

您需要将 event.preventDefault 放在方法的开头,而不是成功回调时

$('#formID').submit(function(event){
    event.preventDefault();
    var InspectionDate = $('#datepicker').val().split('/');
    ...
});
karthikr
2013-04-03

将preventDefault放在第一行,然后如果您希望表单提交,请调用表单元素上的submit方法。通过调用表单元素的submit方法而不是jQuery定义的方法,它将绕过jQuery绑定的submit事件处理程序。

$('#formID').submit(function (event) {
    event.preventDefault();
    var form = this;
    var InspectionDate = $('#datepicker').val().split('/');
    InspectionDate.reverse();
    InspectionDate = InspectionDate.join('-');
    InspectionHour = $('#time_hour').val();
    InspectionMinutes = $('#time_minutes').val();
    var InspectionDateTime = InspectionDate + ' ' + InspectionHour + ':' + InspectionMinutes + ':00';
    $.ajax({
        type: "POST",
        url: "ajax_booking_check.php",
        data: 'InspectionDateTime=' + InspectionDateTime,
        cache: false,
        success: function (response) {
            if (response = 1) {
                alert("An appointment for the selected Date and Time already exists.\n\nDouble Bookings are not possible.\n\nPlease refer to the calender to find an available appointment.");
            } else {
                form.submit();
            }
        }
    });
});
Kevin B
2013-04-03