Search code examples
javascripttwitter-bootstrapbootbox

Form in Bootbox Dialog


I want to display a Bootbox dialog that includes an "OK" button. When the user clicks the "OK" button, it should POST back, with the ID of the message to confirm that the user has viewed the message. The Bootbox dialog is the form. I don't see a way to make the dialog buttons a submit form with hidden fields, which is what I assume is the right way to accomplish my goals.


Solution

  • Thanks to the helpful comments from Isabel Inc and Mistalis, I have a working solution.

    Notes specific to my implementation:

    • The messages contain images that need to be responsive, so I add the appropriate Bootstrap classes to each image
    • The messages may have links. Clicking a link is equivalent to clicking "OK" on the dialog

    And the JavaScript that makes it happen...

    jQuery(function($, window, bootbox, undefined) {
        var accept = function(callback) {
            $.ajax({
                type: 'POST',
                data: {message_id: 244826},
                success: callback()
            });
        };
    
        var $message = $('<p><img src="https://www.gravatar.com/avatar/80fa81938a6d1df92cd101d7fe997a71" alt></p><p>Here is a message from <a href="https://stackoverflow.com/users/244826/sonny">Sonny</a>.</p>');
        $message.find('img').addClass('img-responsive center-block');
        $message.find('a').on('click', function(e) {
            var href = $(this).attr('href');
            if (0 === href.length) {
                return;
            }
            e.preventDefault();
            accept(function() { window.location.href = href; });
        });
    
        bootbox.dialog({
            message: $message,
            closeButton: false,
            buttons: {
                accept: {
                    label: 'OK',
                    callback: function() {
                        accept(function() { window.location.reload(); });
                    }
                }
            }
        });
    }(jQuery, window, bootbox));