2

I'm dynamically creating and adding the following to the DOM:

<a href="my_modal_link" data-toggle="modal">Click me</a>

However, since this content is added dynamically after the page is loaded, the Bootstrap modal is never registered, and clicking the link navigates the browser to the new page rather than displaying it as a modal dialog.

How can I get Bootstrap to know about this dynamically added modal tag so that it will display the content in a modal when the link is clicked? Or, do I have to manually wire up the click event to call .modal()?

1
  • 1
    The answer is yes u have to bind the click event Commented Aug 3, 2015 at 1:57

1 Answer 1

1

As you're creating dynamically the links, you have to use event handlers, something like this

HTML

<a href="#my_modal1" class="modal_links" data-toggle="modal">Click me # 1</a>
<a href="#my_modal2" class="modal_links" data-toggle="modal">Click me # 2</a>
<a href="#my_modal3" class="modal_links" data-toggle="modal">Click me # 3</a>
....
<a href="#my_modalN" class="modal_links" data-toggle="modal">Click me # N</a>

JS

jQuery(function($){
    $("body").on("click",".modal_links",function(ev){
        ev.preventDefault();
        var modalToOpen = $(this).attr("href");
        $(modalToOpen).modal('show'); // also you can use "toggle" instead of "show"
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.