2016-12-27 207 views
1

當創建一個jQuery函數來提交表單時,我需要在發送請求之前首先進行驗證。這裏是我的代碼:jQuery表單提交驗證

$('#Form').submit(function(e){ 
    e.preventDefault(); 
    e.stopImmediatePropagation(); 
    var PhotoID = $('#PhotoID').val(); 
    // I will set the PhotoID to 0 just for testing. 
    var PhotoID = '0'; 
    if (PhotoID == '0') { 
     $('#GlobalError').removeClass('hidden'); 
    } else { 
     return true; 
     $.ajax({ 
      type: "POST", 
      url: $(this).attr('action'), 
      data: $(this).serialize(), 
      beforeSend: function(){ 
       $("#loader").fadeIn(2000); 
      }, 
      success: function(response) { 
      } 
     }); 
    } 
}); 

PhotoID0不同,我想提交表單,並按照正常的頁面轉變,形成action屬性。我知道e.preventDefault()的反義詞是return true;,但不起作用。該功能正在被正確觸發。所以問題就在於表單提交處理。

回答

1

使用return false避免表單提交

$('#Form').submit(function(e){ 
    var PhotoID = $('#PhotoID').val(); 
    // I will set the PhotoID to 0 just for testing. 
    var PhotoID = '0'; 
    if (PhotoID == '0') { 
     $('#GlobalError').removeClass('hidden'); 
     return false; 

    } else { 

     $.ajax({ 
      type: "POST", 
      url: $(this).attr('action'), 
      data: $(this).serialize(), 
      beforeSend: function(){ 
       $("#loader").fadeIn(2000); 
      }, 
      success: function(response) { 
      } 
     }); 
    } 
}); 

但它從來沒有提交,因爲你設置PhotoID值爲0

+1

它的工作。我標記這只是爲了更好地理解代碼。我將在未來爲有相同問題的人更正代碼。謝謝 – rgomez