2012-04-10 125 views
52

我試圖阻止我的表單提交,如果驗證失敗。我試着按照這previous post,但我不爲我工作。我錯過了什麼?停止提交表單,使用Jquery

<input id="saveButton" type="submit" value="Save" /> 
<input id="cancelButton" type="button" value="Cancel" /> 
<script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script> 
<script type="text/javascript"> 

    $(document).ready(function() { 
     $("form").submit(function (e) { 
      $.ajax({ 
       url: '@Url.Action("HasJobInProgress", "ClientChoices")/', 
       data: { id: '@Model.ClientId' }, 
       success: function (data) { 
        showMsg(data, e); 
       }, 
       cache: false 
      }); 
     }); 
    }); 
    $("#cancelButton").click(function() { 
     window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })'; 
    }); 
    $("[type=text]").focus(function() { 
     $(this).select(); 
    }); 
    function showMsg(hasCurrentJob, sender) { 
     if (hasCurrentJob == "True") { 
      alert("The current clients has a job in progress. No changes can be saved until current job completes"); 
      if (sender != null) { 
       sender.preventDefault(); 
      } 
      return false; 
     } 
    } 

</script> 
+0

其功能在上面的代碼是從提交停止形式?什麼是showMsg函數在做什麼?你爲什麼使用sender.preventDefault();發件人參數是一個事件嗎? preventDefault()用於在單擊事件時停止元素的正常行爲。 – DG3 2012-04-10 16:25:46

+0

發件人指的是e:事件 – 2012-04-10 16:34:17

回答

100

此外,AJAX是異步的。所以showMsg函數只有在服務器成功響應後纔會被調用。並且表單提交事件不會等到AJAX成功。

e.preventDefault();作爲點擊處理程序中的第一行。

$("form").submit(function (e) { 
     e.preventDefault(); // this will prevent from submitting the form. 
     ... 

請參見下面的代碼,

我想這是允許的HasJobInProgress ==假

$(document).ready(function() { 
    $("form").submit(function (e) { 
     e.preventDefault(); //prevent default form submit 
     $.ajax({ 
      url: '@Url.Action("HasJobInProgress", "ClientChoices")/', 
      data: { id: '@Model.ClientId' }, 
      success: function (data) { 
       showMsg(data); 
      }, 
      cache: false 
     }); 
    }); 
}); 
$("#cancelButton").click(function() { 
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })'; 
}); 
$("[type=text]").focus(function() { 
    $(this).select(); 
}); 
function showMsg(hasCurrentJob) { 
    if (hasCurrentJob == "True") { 
     alert("The current clients has a job in progress. No changes can be saved until current job completes"); 
     return false; 
    } else { 
     $("form").unbind('submit').submit(); 
    } 
} 
+0

這不會阻止它在所有情況下嗎? – 2012-04-10 16:29:52

+0

您希望事件被允許的條件。您可能需要阻止其提交,然後等待AJAX​​響應並手動提交。 – 2012-04-10 16:30:46

+0

我想讓它被允許HasJobInProgress == False – 2012-04-10 16:32:47

3

嘗試下面的代碼。 e.preventDefault()增加了。這將刪除窗體的默認事件操作。

$(document).ready(function() { 
    $("form").submit(function (e) { 
     $.ajax({ 
      url: '@Url.Action("HasJobInProgress", "ClientChoices")/', 
      data: { id: '@Model.ClientId' }, 
      success: function (data) { 
       showMsg(data, e); 
      }, 
      cache: false 
     }); 
     e.preventDefault(); 
    }); 
}); 

另外,你提到你希望表單在驗證的前提下不提交,但我在這裏看不到代碼驗證?

下面是一些添加了驗證

$(document).ready(function() { 
    $("form").submit(function (e) { 
     /* put your form field(s) you want to validate here, this checks if your input field of choice is blank */ 
    if(!$('#inputID').val()){ 
     e.preventDefault(); // This will prevent the form submission 
    } else{ 
     // In the event all validations pass. THEN process AJAX request. 
     $.ajax({ 
      url: '@Url.Action("HasJobInProgress", "ClientChoices")/', 
      data: { id: '@Model.ClientId' }, 
      success: function (data) { 
       showMsg(data, e); 
      }, 
      cache: false 
     }); 
    } 


    }); 
}); 
+0

我實際上並沒有驗證一個領域。代碼的這個ajax部分調用一個方法來檢查客戶端的作業是否已經在進行中。我不希望允許同一客戶端的多個作業入隊。 – 2012-04-10 16:39:36

+0

e.preventDefault()然後將解決您的問題 - > – Downpour046 2012-04-10 16:40:50

15

使用的示例這個太:

if(e.preventDefault) 
    e.preventDefault(); 
else 
    e.returnValue = false; 

Becoz e.preventDefault()不支持IE(一些版本)。在IE中它是e.returnValue =假

+9

萬一您使用jQuery,您可以安全地使用'e.preventDefault()'。 jQuery會照顧X瀏覽器的兼容性。 – staabm 2014-03-11 10:00:44

+0

酷,不知道 – gskema 2015-02-10 23:21:25

+0

從[jQuery on](http://api.jquery。com/on /)API:「從事件處理函數返回false將自動調用'event.stopPropagation()'和'event.preventDefault()'。」它繼續說:「一個'false'值也可以作爲'function(){return false;}'' – Paul 2015-08-21 19:01:15

3

一種不同的方法可以是

<script type="text/javascript"> 
    function CheckData() { 
    //you may want to check something here and based on that wanna return true and false from the   function. 
    if(MyStuffIsokay) 
    return true;//will cause form to postback to server. 
    else 
     return false;//will cause form Not to postback to server 
    } 
    </script> 
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" })) 
    { 
    ......... 
    ......... 
    ......... 
    ......... 
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/> 
    }