Load Bootstrap Modal from AJAX using jQuery

index.html
<!--
putting the link in data-href instead of href removes the js error
"Uncaught Error: Syntax error, unrecognized expression: /path/to/file
-->
<a class="btn btn-primary" data-href="modal_content.html" data-toggle="modal" href="#">Show Modal</a>

modal_content.html
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title">Modal Title</h4>
        </div>
        <div class="modal-body">
            Modal Body
        </div>
        <div class="modal-footer">
            <button class="btn btn-default" data-dismiss="modal" type="button">
                Close
            </button>
            <button class="btn btn-primary" type="button">
                Save Changes
            </button>
        </div>
    </div> <!-- /.modal-content -->
</div> <!-- /.modal-dialog -->

script.js

$('body').on('click','a[data-toggle="modal"]',function(e){
    var action = $(this).attr('data-href');
    $.ajax({
        url : action,
        type: "GET",
        success: function(response) {
            $('<div class="modal fade"></div>').html(response).modal();
        }
    });
    e.preventDefault();
});

// should use 'hidden' for bootstrap 2
$('body').on('hidden.bs.modal', '.modal', function() {
    $(this).remove();
});

Comments

  1. Hi Lewis,

    What will gonna be, if on your AJAX modal body has a DOM Script function like datepicker? can you show to us?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. thanks for the tip!

    ReplyDelete

Post a Comment