简体   繁体   中英

jQuery continue form submission with selected submit button

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.

My HTML looks like this:

<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:

$('#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() .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM