简体   繁体   中英

Two Submit Buttons on Single Form

Is it possible to have two submit buttons on a single form, one of which launches the submit but also passes a parameter to the URL? Perhaps using js/jquery to intercept the action and append the param somehow. ie,

<form action="/doStuff" method="post">
    <input id="name" type="text"></input>
    <button id="save" type="submit">Save</button>
    <button id="save-with-param" type="submit">Save as Draft</button>
</form>

Clicking save would send:

localhost:8080/myApp/doStuff

and clicking save-with-param would send:

localhost:8080/myApp/doStuff?param=XYZ

On all moder browsers, you can use formaction attribute:

<form action="/doStuff" method="post">
    <input id="name" type="text"></input>
    <button id="save" type="submit">Save</button>
    <button id="save-with-param" type="submit" formaction="/doStuff?param=XYZ">Save as Draft</button>
</form>

To support older browsers, eg IE9<, you could add support using:

;(function ($) {
    $(function () {
        if (typeof document.createElement('input').formAction === "undefined") {
            $(':submit[formaction]').closest('form').data('defaultFormAction', this.action).on('submit', function () {
                var $focused = $(':focus');
                $(this).attr('action', $focused.is('[formaction]') ? $focused.attr('formAction') : $(this).data('defaultFormAction'));
            });
        }
    });
}(jQuery));

If you want to do this with jQuery:

$(document).ready(function() {
    $("#save-with-param").on("click", function() {
        var action = $('form').attr('action') + "?param=XYZ";
        $('form').attr('action', action);
    });
});

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