2013-04-03 91 views
0

点击提交按钮时,我试图抓住提交并做一个快速的AJAX请求,看看表单中指定的时间和日期是否已经存在预订。如果是,请停止提交表单并提醒用户预订日期和时间已经存在!如果没有预订,请继续并提交表格。对于我的生活,我不能让.preventDefault工作,除非我把它放在提交函数的末尾。任何想法和指针都非常感谢,我一直坚持了三个小时,似乎并没有得到任何快速。我99%肯定我只是一个白痴,所以提前道歉!Jquery:无法让.preventDefault工作

这里是我的代码:

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

你是如何使用preventDefault的? – karthikr 2013-04-03 20:54:23

+0

抱歉,不确定你的意思是我如何使用preventDefault? – 2013-04-03 20:56:32

+0

抱歉..忘了删除这条评论..看到它在成功回拨 – karthikr 2013-04-03 20:57:58

回答

0

放置的preventDefault作为第一行,那么如果您希望表单提交,请在表单元素上调用submit方法。通过调用表单元素的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(); 
      } 
     } 
    }); 
}); 
+0

谢谢凯文......我知道这会很简单!非常感激。 – 2013-04-03 21:00:11

2

你需要把event.preventDefault在方法的开始,而不是在成功回调

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

干杯!现在明白了,知道这将是简单的事情。 – 2013-04-03 21:01:04