rob.m
rob.m

Reputation: 10571

How to open a modal in bootstrap if this is loaded via ajax?

I am calling a div where the modal is via Ajax. Once the div and its modal has been loaded, the button won't open the modal. The code below is the modal structure, it is just a plain modal from bootstrap, and this has been loaded via ajax:

<div class="ajax-loaded-item">
 <button type="button" class="btn btn-primary" data-toggle="modal" data-target="myModalZ">Large modal</button>

 <div class="modal fade" id="myModalZ" tabindex="-1" role="dialog" aria-labelledby="myModalLabelZ" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="myModalLabelS">Filter our work</h2>
            </div>
            <div class="modal-body">
                Content.....
            </div>
        </div>
    </div>
 </div>
</div>

If it is the case that I need to reload bootstrap.js where the modal jQuery is as the content is now loaded via ajax, is there a sort of init modal call I can do after my own ajax callback?

Upvotes: 1

Views: 1555

Answers (3)

cejor6
cejor6

Reputation: 41

As of Bootstrap v5.0+ they have changed the way that you launch a modal from JavaScript (see here).

Now, in order to launch the modal the syntax is as follows:

const modal = new bootstrap.Modal('#myModal', options);
modal.show();

On that same page, it explains what the optional 'options' argument can be.

Upvotes: 0

Code Lღver
Code Lღver

Reputation: 15603

You can use the jQuery to open the modal:

$(document).ready(function(){
    $('button[data-target="myModalZ"]').click(function(){
        $('#myModalZ').modal('show');
    });
});

More Documentation is here.

EDITED:

$(document).ready(function(){
    $('button[data-target="myModalZ"]').click(function(){
        if($('#myModalZ').length){
           $('#myModalZ').modal('show');
        } else {
           alert('Your message');
        }
    });
});

Upvotes: 2

Shreejibawa
Shreejibawa

Reputation: 1868

First append received content inside body somewhere. Then trigger modal manually.

$.ajax(
    {
        url: "http://www.example.com/someAPI", 
        success: function(result){
            // Append content somewhere

            // Init button click event once your content is ready
            $('button[data-target="myModalZ"]').click(function(){
                $('#myModalZ').modal('show');
            });

    }
});

Please check out full documentation here.

Upvotes: 0

Related Questions