Old post, but I like to share, since I have the same case, but I finally knew the problem:
The problem is this: we are creating a function to work with the specified HTML element, but the HTML element associated with this function has not yet been created (since the element was dynamically generated). For this to work, we must create the function at the same time that we create the element. An element first than to associate a function with it.
Just a word, a function will only work with the element created in front of it. Any elements created dynamically mean after it.
But please check this sample, which did not take into account the above case:
<div class="btn-list" id="selected-country"></div>
Dynamically added:
<button class="btn-map" data-country="'+country+'">'+ country+' </button>
This function works well by pressing a button:
$(document).ready(function() { $('#selected-country').on('click','.btn-map', function(){ var datacountry = $(this).data('country'); console.log(datacountry); }); })
or you can use the body:
$('body').on('click','.btn-map', function(){ var datacountry = $(this).data('country'); console.log(datacountry); });
compare with this what doesn't work:
$(document).ready(function() { $('.btn-map').on("click", function() { var datacountry = $(this).data('country'); alert(datacountry); }); });
hope this helps
Sulung Nugroho Sep 27 '16 at 14:02 2016-09-27 14:02
source share