jQuery submit()不包括提交的按鈕
我有一個表單有幾個元素和兩個提交按鈕,一個是“儲存”,另一個是“刪除”.在“刪除”按鈕上,我使用jQuery對話方塊確認使用者想要刪除.那麼如果他們確認,我提交表格.問題是jQuery.submit()在釋出時不包含原始的提交按鈕,所以我無法在伺服器上區分“從儲存中刪除”,因為它們都使用相同的形式.如果我刪除了jQuery對話方塊,那麼提交按鈕的值按預期的方式釋出.這是很常見的,我希望有人可以分享一個解決方案.我已經搜尋,找不到任何有用的東西(只是我或者是最近吮吸谷歌?)
感謝任何幫助…
編輯:
提交按鈕確實設定了名稱和值.它工作正常,如果不使用jQuery.submit()
基於karim79的答案:
$("input[type=submit], input[type=button], button").click(function(e) { var self= $(this), form = self.closest(form), tempElement = $("<input type='hidden'/>"); // clone the important parts of the button used to submit the form. tempElement .attr("name", this.name) .val(self.val()) .appendTo(form); // boom shakalaka! form.submit(); // we don't want our temp element cluttering up the DOM, do we? tempElement.remove(); // prevent default since we are already submitting the button's form. e.preventDefault(); });
更新:
我只是意識到上面的程式碼可能不是你要找的:
如果你正在呼叫form表單元素($(“form”).submit();),你將需要這樣的東西:
$("form").submit(function(){ var form = $(this); $("input[type=submit], input[type=button], button", form).eq(0).each(function(){ var self= $(this), tempElement = $("<input type='hidden'/>"); // clone the important parts of the button used to submit the form. tempElement .attr("name", this.name) .val(self.val()) .appendTo(form); }); });
這將在表單提交之前將第一個按鈕元素的名稱和值新增到DOM(我不知道預設瀏覽器的行為在這裡).請注意,這不會從DOM中刪除tempElement.如果出現錯誤,並且表單未提交,則該元素將保留,如果您不理會該問題,您將遇到問題.
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/4605671/jquery-submit-doesnt-include-submitted-button