简体   繁体   中英

Confirm form submit with two buttons in BootboxJS

I'm using Bootbox.js to show a confirmation box prior to submitting a form. The form has two submit buttons that handle two different actions. I was successful in showing the dialog and submitting the form, however the value of the button that was clicked is not included in the request. This is obvious, because by submitting the form manually no buttons were clicked. As I need to have a working form with and without javascript, I can't use hidden fields with a value changed at runtime by javascript. I then tried triggering the click event on the button itself when I leave the popup dialog, however I don't know how I could understand which button was originally clicked. Also, the click will probably trigger another submit event causing an infinite loop. How can I prevent that?

<form name="myform" action="myaction" method="post">
    ...

    <button type="submit" name="decline" value="decline">Decline</button>
    <button type="submit" name="accept" value="accept">Accept</button>
</form>

$(document).ready(function() {
    $('form[name="myform"]').submit(function(e) {
        bootbox.confirm({
            message: '...',
            callback: function(result) {
                if (result) {
                    $('button[name="accept"]').click();
                }
            }
        });

        e.preventDefault();
    }
});

An (admittedly brute-force) method of making your current script work is to create a sentinel variable that you toggle on the submission of your form:

$(function() {

    var firstClick = true;

    $('form[name="myform"]').submit(function(e) {

        if(firstClick === true){

            firstClick = false;

            bootbox.confirm({
                message: '...',
                callback: function(result) {
                    if (result) {
                        $('button[name="accept"]').click();
                    }
                }
            });

            e.preventDefault();
        }
    }
});

This lets you handle the form submission the first time the submit event is triggered, with subsequent submit events being allowed to submit the page.

It's also worth nothing ( per the HTML spec ) that

A button (and its value) is only included in the form submission if the button itself was used to initiate the form submission.

So your two buttons (Accept and Decline) could share the same name attribute, with only the button that was clicked reporting it's 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