I’m basically developing a plugin that generates table rows dynamically to display content on a defined page, when generating I want it to display a button on each row that actives an Ajax request when clicked, I’ve tried appending an ID and doing the jQuery onClick to perform this, yet it’s not showing my test alert()
Here’s the jQuery code I’m using :
jQuery(document).ready(function(){
jQuery("#submit").click(function(event) {
//Stop the form processing
event.preventDefault();
//Get the username value
var Username = jQuery('#username').val();
jQuery.ajax({
type: "GET",
crossDomain: true,
url: apiURL + "video/" + Username + "/views/",
success: function(data) {
Parsed = jQuery.parseJSON(data);
jQuery.each(Parsed.user_media, function(i,v){
jQuery("#results").append("<tr><td><button type='submit' id='addtoPlaylist'>Add to Playlist</button></td></tr>");
});
},
});
});
jQuery("#addtoPlaylist").click(function(event) {
alert('Working!');
});
});
Everything is working perfect as such as the Ajax calls and returning the table rows, It’s just when I’m trying to utilise the .click()
based on the <button></button>
it just doesn’t seem to activate nor throw any errors into console.
That’s happened because you’re adding link listen at document ready. At this time you’re ajax call hasn’t fired yet and the element don’t exist in page.
You must create a separate function and call it in ajax return statement.
Notice that different buttons must have different ids.
The soluiton should been somethingh like
});
Try this
Use jQuery event delegation for generated elements:
Try
i prefer to use jQuery.delegate on future elements.
I’ll suggest not using delegated event handlers, but instead create the elements the proper way with jQuery :
and note that you are appending multiple elements with the same ID.