Skip to content Skip to sidebar Skip to footer

Dynamically Created Bootstrap3 Modals Do Not Work

I have a page with dynamically generated list of items. Every item has button toggling modal window with more info but modal do not appear. The modals are placed right after body o

Solution 1:

Here is step by step Implementation in one of my project, hope it will help.

1-Suppose its your List, which have button in it(MVC Razor view example).

@foreach (var list in ListCollection)
 {                            
  <button type="button" class="btn btn-xs  btn-primary" data-toggle="modal" data-target="#exampleModal" data-id="@list.ID> Details </button>
 }

2-Here I have put data-id to each button to open a modal for this button in the list.

3-Each button will open the modal with more info using script(script below).

<divclass="modal fade"id="exampleModal"tabindex="-1"role="dialog"aria-labelledby="exampleModalLabel"><divclass="modal-dialog"role="document"><divclass="modal-content"><divclass="modal-header"><buttontype="button"class="close"data-dismiss="modal"aria-label="Close"><spanaria-hidden="true">&times;</span></button><h4class="modal-title"id="exampleModalLabel">Title Here</h4></div><divclass="modal-body">
              //Put here more details of the item, by Ajax call or any thing you like
            </div><divclass="modal-footer"><buttontype="button"class="btn btn-default"data-dismiss="modal">Close</button></div></div></div></div>

4-Now the script part

$(document).ready(function () {
        $('#exampleModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget);//Button which is clickedvar clickedButtonId= button.data('Id');//Get id of the buttonvar modal = $(this);
            modal.find('.modal-body').text(clickedButtonId);
//Id of the clicked button which i have put inside the modal-body div class or put info here using ajax call for the button that button.//Ajax call to get the more details of clicked button in the list.

            $.ajax({
                url: "URL",
                type: "POST",
                data: JSON.stringify({ id: clickedButtonId}),
                dataType: 'JSON',
                contentType: "application/json",
                success: function (response) {
                    modal.find('.modal-body').text(response);//Put here more info using ajax
                }
                  ,
                error: function () {

                }
            });

        })

    });

Post a Comment for "Dynamically Created Bootstrap3 Modals Do Not Work"