Playing with Bootbox

In this example, we will use bootbox.js to display and validate a login form inside a modal.

Initially, the login form isn't displayed:





When click the login button, we will show up the modal. We might need to reset the previous form values using the resetForm method.


const loginForm = document.getElementById('loginForm');

const fv = FormValidation.formValidation(loginForm, {
    fields: {
        ...
    },
    plugins: {
        ...
    },
});

document.getElementById('loginButton').addEventListener('click', function() {
    bootbox
        .dialog({
            title: 'Login',
            message: loginForm,
            size: 'small',
            show: false // We will show it manually later
        })
        .on('shown.bs.modal', function() {
            // Show the login form
            loginForm.style.display = 'block';
            
            // Reset form
            fv.resetForm(true);
        })
        .on('hide.bs.modal', function() {
            // Bootbox will remove the modal (including the body 
            // which contains the login form) after hiding the modal
            // Therefor, we need to backup the form

            loginForm.style.display = 'none';
            document.body.appendChild(loginForm);
        })
        .modal('show');
});

You can take a look at the Code tab to see the full code:

If you want to use Ajax to submit the form, we can trigger the core.form.valid event:


const fv = FormValidation
    .formValidation(loginForm, {
        fields: {
            ...
        },
        plugins: {
            ...
        },
    })
    .on('core.form.valid', function() {
        // Send the form data to back-end
        // You need to grab the form data and create an Ajax request to send them
        
        // Since the Bootbox and Bootstrap require jQuery
        // we can use jQuery methods for getting the form data
        // and creating Ajax request
        
        $.post($(loginForm).attr('action'), $(loginForm).serialize(), function(result) {
            // ... Process the result ...

            // Hide the modal containing the form
            $(loginForm).parents('.bootbox').modal('hide');
        }, 'json');
    });