Jquery:无法让.preventDefault工作

时间:2013-04-03 20:52:58

标签: jquery preventdefault

点击提交按钮,我试图抓住提交并执行快速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 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

$('#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();
            }
        }
    });
});