jQuery使用选定的提交按钮继续表单提交

时间:2023-01-23 20:31:30

I'm intercepting the submission of a form with jQuery and validating a few things before continuing submission. The problem is that there are multiple submit buttons with different actions on the page and when I try to call form.submit() after validation the name tag of the submit button is lost / not sent in the request-params.

在继续提交之前,我正在拦截使用jQuery提交表单并验证一些内容。问题是页面上有多个提交按钮和不同的操作,当我尝试在验证后调用form.submit()时,提交按钮的名称标签丢失/不在request-params中发送。

My HTML looks like this:

我的HTML看起来像这样:

<input type="submit" name="publish" value="Publish">
<input type="submit" name="draft" value="Save as draft">

and in the coffeescript code I'm intercepting form submission with:

并且在coffeescript代码中我正在截取表单提交:

$('#foo-form').submit (e) ->
  e.preventDefault()
  form = this

  # DO WORK...
  # A callback eventually calls form.submit()

I'd like to somehow store which button was clicked and pass it on to form.submit().

我想以某种方式存储单击了哪个按钮并将其传递给form.submit()。

1 个解决方案

#1


0  

Add a click event handler to each submit button that adds (or updates) a hidden input with the values.

为每个提交按钮添加一个单击事件处理程序,该按钮用值添加(或更新)隐藏的输入。

function store_submit_value (ev) {
    var $frm = jQuery(this.form);
    var $input = $frm.find("input.submit_value");
    if (!$input.length) {
        $input = jQuery("<input />")
            .attr("type", "hidden")
            .addClass("submit_value")
            .appendTo($frm);
    }
    $input.attr("name", this.name).val(this.value);
}

jQuery("#foo-form").on("click", 'input[type="submit"]', store_submit_value);

#1


0  

Add a click event handler to each submit button that adds (or updates) a hidden input with the values.

为每个提交按钮添加一个单击事件处理程序,该按钮用值添加(或更新)隐藏的输入。

function store_submit_value (ev) {
    var $frm = jQuery(this.form);
    var $input = $frm.find("input.submit_value");
    if (!$input.length) {
        $input = jQuery("<input />")
            .attr("type", "hidden")
            .addClass("submit_value")
            .appendTo($frm);
    }
    $input.attr("name", this.name).val(this.value);
}

jQuery("#foo-form").on("click", 'input[type="submit"]', store_submit_value);