Dynamically build Twitter Bootstrap modal

Update:

Since posting this, I’ve found an elegant bootstrap 3 modal wrapper function here, which doesn’t require adding a div to the html code.


Here’s a code sample that demonstrates this. To use, just add a div in your <body> (inside bootstrap’s <div class=”container”>, for example:

<div id="idMyModal"></div>

and then you can use it via:

var header = "This is my dynamic header";
var content = "This is my dynamic content";
var strSubmitFunc = "applyButtonFunc()";
var btnText = "Just do it!";
doModal('idMyModal', header, content, strSubmitFunc, btnText);

To close the modal, issue a call to hideModal, also defined below:

function doModal(placementId, heading, formContent, strSubmitFunc, btnText)
{
    var html="<div id="modalWindow" class="modal hide fade in" style="display:none;">";
    html += '<div class="modal-header">';
    html += '<a class="close" data-dismiss="modal">×</a>';
    html += '<h4>'+heading+'</h4>'
    html += '</div>';
    html += '<div class="modal-body">';
    html += '<p>';
    html += formContent;
    html += '</div>';
    html += '<div class="modal-footer">';
    if (btnText!='') {
        html += '<span class="btn btn-success"';
        html += ' onClick="'+strSubmitFunc+'">'+btnText;
        html += '</span>';
    }
    html += '<span class="btn" data-dismiss="modal">';
    html += 'Close';
    html += '</span>'; // close button
    html += '</div>';  // footer
    html += '</div>';  // modalWindow
    $("#"+placementId).html(html);
    $("#modalWindow").modal();
}


function hideModal()
{
    // Using a very general selector - this is because $('#modalDiv').hide
    // will remove the modal window but not the mask
    $('.modal.in').modal('hide');
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)