2012-02-21 220 views
5

這裏是我的代碼:後點擊禁用提交按鈕

<form name='frm' id='frm' action='load.asp' method='post' onSubmit='return OnSubmit(this)' style='margin-top:15px'> 
    <input type='submit' name='send' id='send' onclick="this.disabled=true;return true;" value='Send' title='test'> 
</form> 

我要執行我的onsubmit功能,我想所需提交的頁面。 在我的網站,沒有提交和無功能

我試圖在這裏重複它,但形式似乎被張貼和我的功能從來沒有被執行... http://jsfiddle.net/V7B3T/1/

而且我不知道我應該何時重新激活按鈕。

我應該在document.ready中還是在onSubmit函數中執行它?

所以,如果有人可以修理小提琴:)之後,我會比較它與我的代碼。 我想:S I迷路

感謝所有

回答

14

如果你想驗證表單或做任何改動的提交之前只提交如果表單是有效的,你可以做這樣的事情:

<form id="frm" action="load.asp" method="post" enctype="multipart/form-data"> 
    <input type="submit" name="send" id="send" value="Send" title="test"> 
</form> 

和JavaScript代碼:

$('#frm').bind('submit', function (e) { 
    var button = $('#send'); 

    // Disable the submit button while evaluating if the form should be submitted 
    button.prop('disabled', true); 

    var valid = true;  

    // Do stuff (validations, etc) here and set 
    // "valid" to false if the validation fails 

    if (!valid) { 
     // Prevent form from submitting if validation failed 
     e.preventDefault(); 

     // Reactivate the button if the form was not submitted 
     button.prop('disabled', false); 
    } 
}); 

這裏有一個工作fiddle

+0

正是我需要的,非常感謝。 – GregM 2012-02-21 14:42:48

0

如果你不想提交頁面本應該做的伎倆:

onclick="this.disabled=true;return false;" 
+0

對不起,我的問題搞砸了,我想提交頁面,我想要執行onsubmit函數 – GregM 2012-02-21 13:45:55

4

我肯定會認爲代碼移到外部JS(和CSS)文件屬於它的地方,但這應該工作:

onclick="this.disabled=true;this.parentNode.submit();" 

既然你禁用提交按鈕的onclick它將一旦實際形式submissi被禁用點擊發生(onclick在此之前發生)。用JS提交表單應該可以做到。

http://jsfiddle.net/V7B3T/4/

編輯:關於重新啓用按鈕,將要發生後,你的OnSubmit()功能已經跑我猜。

+0

謝謝,我試過這個,但是我的onSubmit函數沒有執行 – GregM 2012-02-21 13:50:56

+0

好的,然後簡單地運行你的'OnSubmit()'函數,而不是提交表單:'onclick =「this.disabled = true; OnSubmit(this.parentNode);' – powerbuoy 2012-02-21 13:51:45

+0

最短,最簡單的解決方案,謝謝 – 2017-09-11 06:43:19

5

如果您的表單實際上做了回發,您將有效更改頁面,因此無需擔心重新啓用按鈕(頁面加載後會發生這種情況)。

此外,由於您使用的是jQuery,因此您可以正確使用它,並通過附加使用jQuery函數的事件處理程序而不是HTML元素上的onclick,onsubmit等屬性來分隔HTML標記和Javascript。

更新的HTML:

<form name='frm' id='frm' action='http://jsfiddle.net/' enctype='multipart/form-data' method='post' style='margin-top:15px'> 
    <input type='submit' name='send' id='send' value='Send' title='test'> 
</form> 

更新的Javascript:

function submitForm(form) { 
    alert("submitted"); 
} 

$('#send').click(function(e) { 
    this.disabled = true; 
}); 

$('#frm').submit(function(e) { 
    submitForm(this);  
}); 

Working jsFiddle

你需要包裝,在一個$(document).ready(function() {...});呼籲實際頁面上使用 - 我離開因爲jsFiddle無論如何都會執行任何提供的Javascript onLoad。

+0

不適用於最新版本Chrome。看起來,禁用按鈕可以防止表單提交。 – jmarceli 2015-08-13 07:44:38

+0

@jmarceli是的,看起來他們已經改變了一些東西,我想知道這是否是故意的... – 2015-08-13 08:12:29