Reputation: 327
Having a frustrating time, made even worse that the examples I see everywhere are not working in this instance. My assumption is because I am not understanding what elements are being loaded in which order.
The question is common enough, I have a button that I want to pass data from into the modal it opens. Let's say I want to pass in the id. My first idea was something like this which is the typical answer on Stack Overflow:
HTML:
<button class="btn btn-primary btn-block" data-toggle="modal" data-target="#myModal" id="product-button">Product Name</button>
JavaScript:
$(function() {
$('#product-button').click(function() {
var productId = $(this).attr('name');
$(".modal-body #testContainer").val(productId);
});
});
This is seen here: Passing data to a bootstrap modal
However, this appears not to work for me. The kicker for my scenario is that the buttons are generated dynamically and I am wondering if because I've wrapped everything in a helper function and it ties itself to the page before the dynamic buttons are created and therefore doesn't know they exist and to listen for a .click event (they are created through a search, the buttons are the results of the search)
Anybody have any ideas on how I can go about passing data to a modal with this limitation?
Upvotes: 0
Views: 88
Reputation: 62488
If the buttons are generated dynamically, you have to use event-delegation to make it work:
$(function() {
$(document).on('click','#product-button',function() {
var productId = $(this).attr('name');
$(".modal-body #testContainer").val(productId);
});
});
Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.
Upvotes: 3