Reputation: 313
I have a <div>
with id="modal"
generated dynamically with the jQuery load()
method:
$(".show-product").click(function(){
$("#modal").load($(this).attr("href"), function(e){
$(".details").click(function(){
I had to put the code in the click event of the class '. detail' within this code, because if what I had was not running. I have the code in both places, since I also use it outside of the modal, being doubled.
Something similar happens to me with a table that I build dynamically, thanks to an example that I saw here, Stack Overflow. It does not capture the click event, the window darkens as when it opens the modal, but it does not call the url or load. This code:
$.ajax({
url : form,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR){
$("#dynamicTable>tbody>tr").remove();
var x = [];
$.each(dataSet, function(i, item) {
x.push('<tr><td><a href="/product/' + item.product.id + '" class="details" data-toggle="modal" data-target="#modal">' + item.product.name + '</a></td>');
x.push('<td>' + item.product.name + '</td></tr>');
});
$("#dynamicTable>tbody").html(x.join(""));
},
error: function(jqXHR, textStatus, errorThrown){
alert('Not product found!');
}
});
event.preventDefault()
I think that in both cases events is not working because they are loaded dynamically. I was looking for here and on Google and try to make changes but it does not work without having to duplicate code (in the event $(document).ready
and at each event that loads data dynamic, the modal window and load table).
Changes:
$(document).ready(function() {
//$(".show-product").click(function(){
$(".show-product").on("click", function(e){
$("#modal").load($(this).attr("href"), function(e){
//$('.details').click(function(e){
// ........
});
});
// Added
$(".details").on("click", function(e){
..........
..........
});
});
With these changes still do not work, only works in pages with static content, when I get to have the content dynamic (modal, table dynamics and others) does not working events.
What do I do wrong?
Upvotes: 1
Views: 1255
Reputation: 313
Delegating the event to body
fixes the issue since it avoids attaching handlers directly to the dynamically-generated elements:
$(document.body).on("click", ".details", function(e){
...
});
Upvotes: 2
Reputation: 2290
You should use jquery on()
for events on dynamically created elements.
Docs: http://api.jquery.com/on/
Upvotes: 1