2013-04-02 243 views
3

我有一個帶有2個提交按鈕的表單。如何通過JQuery提交表單時點擊提交按鈕

<form class="myForm"> 
    <!-- Some Inputs Here --> 
    <input type="submit" name="firstSubmit" value="first submit" /> 
    <input type="submit" name="secondSubmit" value="second submit" /> 
</form> 

我通過JQuery提交此表單。

$(".myForm").submit(function(){ 
     var submitButton = ? //I need to catch the submit button that was clicked 
}); 

如何知道哪個提交按鈕被點擊?

+1

長相酷似http://stackoverflow.com/questions/3577469/form-onsubmit-determine-which-submit-button-was-pressed –

+0

http://stackoverflow.com/questions/5721724/jquery如何得到哪個按鈕被點擊的表單提交 對此的答案是鏈接的主題上的最佳答案。 – Swapnull

回答

9
$('input[type="submit"]').on('click', function(){ 
     $('.myForm').data('button', this.name); 
}); 

$(".myForm").on('submit', function(){ 
    var submitButton = $(this).data('button') || $('input[type="submit"]').get(0).name; 
}); 
+0

使用'.submit()'是必須的,無論如何要使用它提交按鈕? –

+0

@AliBassam - 當然,只需將點擊的按鈕存儲在數據()中。 – adeneo

+0

這比我見過的選擇好得多,如果按下回車鍵,這甚至會默認爲第一個按鈕的名稱。雖然真的,這應該是使用/提交按鈕的值,而不是它的名字。 – Triynko

相關問題