2016-01-28 89 views
0

問題我有我的MVC應用程序中的用戶點擊提交按鈕張貼表單的頁數。有時用戶將點擊提交,因爲沒有立即發生,請再次單擊它。因此,表單提交兩次。爲了防止這種情況,我有以下的JavaScript代碼:MVC - 與用戶雙擊提交按鈕

// When the user submits the form, disable the Save button so there is no chance 
// the form can get double posted. 
$('#form').submit(function() { 
    $(this).find('input[type=submit]').prop('disabled', true); 

    return true; 
}); 

此代碼禁用提交按鈕,使用戶無法點擊兩次。這工作正常。但是,如果表單上存在客戶端驗證錯誤,則「提交」按鈕將被禁用,但表單不會發布,現在用戶無法發佈表單。是否有可以對JS代碼進行更改以檢測是否存在客戶端驗證錯誤,如果是,我要麼不禁用Submit按鈕,要麼重新啓用它?

回答

3

如果您正在使用jQuery驗證,您可以查看是否窗體是禁用按鈕之前有效:

$('#form').submit(function() { 
    if ($(this).valid()) { 
     $(this).find('input[type=submit]').prop('disabled', true); 
    } 
}); 
+0

這似乎工作的偉大。謝謝。 –

-1

開關它周圍。

$("input[type='submit']").on("click", function (event) { 
    event.preventDefault(); 
    $(this).prop("disabled", true); 
    // perform error checking 
    if (noErrors) { 
     $("#form").submit(); 
    } 
    else { 
     $(this).prop("disabled", false); 
    } 
}); 
+0

什麼是錯誤檢查? –

+0

無論你想要它。你可以有一個函數來檢查你輸入的值,你可以使用jquery驗證,真的是你喜歡的任何東西。我通常有一個checkFormForErrors()函數,根據每個字段的自定義需求驗證我的所有輸入。 – mhodges

+0

驗證已通過MVC和我放在各個字段中的屬性完成。我需要知道驗證是否通過或失敗,然後採取相應措施。 –

0

你可以嘗試這樣的事情:

<button id="subButton" /> <!-- do not use type="submit" because some browsers will automatically send the form --> 

的Javascript:

$('#subButton').click(function (e) { 
    e.preventDefault(); //prevent browser's default behaviour to submit the form 
    $(this).prop('disabled', true); 
    doValidation(); 
}); 

var pTimeout; 
function doValidation() { 
ajaxLoader.show(); //lock the screen with ajaxLoader 
var form = $('#registerForm'); 
var isPending = form.validate().pendingRequest !== 0; // find out if there are any pending remote requests ([Remote] attribute on model) 
if (isPending) { 
    if (typeof pTimeout !== "undefined") { 
     clearTimeout(pTimeout); 
    } 
    pTimeout = setTimeout(doValidation, 200); //do the validation again until there are no pending validation requests 
} 
var isValid = form.valid(); //have to validate the form itself (because form.Valid() won't work on [Remote] attributes, thats why we need the code above 
if (!isPending) { 
    ajaxLoader.hide(); 
    if (isValid) { 
     $('#registerForm').submit(); //if there are no pending changes and the form is valid, you can send it 
    } 
    else { 
     $('#subButton').prop('disabled', false); //else we reenable the submit button 
    } 
}};