0
votes

I am returning an Json object from an local API, it's working fine, with the object I feed my table with rows and columns, each column has a search button, which should open a modal with more detailed info about that line, which was already loaded with the table.

Here is a sample of my button looks like:

        <tr>
    ...
            <td><button type="button" class="btn btn-primary form-control"
         id="id5bb3b60d870f3809e8e4403d" data-toggle="modal" 
data-target="#5bb3b60d870f3809e8e4403dmodal">+</button></td>
            </tr>

And here is a modal example:

<div id="5bb3b60d870f3809e8e4403dmodal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="5bb3b60d870f3809e8e4403dLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="5bb3b60d870f3809e8e4403dLabel">whatever</h5>
            </div>
            <div class="modal-body"></div>
            <div class="modal-footer"></div>
        </div>
    </div>
</div>

As you can see, my data target and div id are matching, I also tried to remove the aria-labelledby and aria-hidden, if I use the browser inspector I can see that the modal is already loaded. I also can successfully use the getElementById using my modal id. I'm sorry that this is a noob mistake, but I already wasted a whole day trying to solve it. I get no exception, nor error, nor any view of the modal.

1
Can you please post a complete example that repros the problem? - Zim
Make sure you have all required nested divs for a modal, for eg. modal-dialog, modal-content etc. After that, make sure no two divs have the same id (this definitely causes the modal to not show up) - Bivo Kasaju
It's because your table content is loaded dynamically. Same issue when you have listener for a button click event but the button is loaded and built dynamically. The click event won't work and you have to use $.on('click') instead. - David Liang

1 Answers

0
votes

@David Liang was right, since I'm loading my table dynamically it didn't works.

To solve it using JQuery delegation I just needed to:

$("#rastreioTable tbody").on('click', 'button', function (event) {
    $("#" + this.id + "modal").modal();
});

Where "rastreioTable" was my table Id and "tbody" was the element where the rows where being loaded. As far as I could understand the issue is that when we add a new item or modify an html element you broke the event handlers that were loaded initially.

If it was to be solved with vanilla JS an event listener would solve it, something like the code below:

document.getElementById("rastreioTable").addEventListener('click', function (e) {
if (e.target.type == "button") {
        $("#" + e.target.id + "modal").modal();
}
}, false);

Here I would also need to add an if to check if the item pressed is a button, because the event would be triggered if the user clicked anywhere in the table.