Reputation: 10066
All, I've got the following jQuery code:
jQuery("#add_timeline_row").on("click", function(event){
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
}
var total_rows = jQuery('[name="timeline_num[]"]').length;
alert(total_rows);
total_rows = total_rows + 1;
jQuery.post(site_url + "add_row.php", { total: total_rows },
function(response) {
jQuery('#timeline_table tr:last').after(response);
});
});
This works fine and basically adds a row after my DOM has finished loading if the user clicks on the button. I've added the .on function so jQuery recognizes it since the DOM was already loaded. My issue is that it creates a select field. I then have the following jQuery to remove a row if a certain select value is selected:
jQuery('.event_selection').on('change' ,function(){
var selected_event = jQuery(this).val();
var fullId = jQuery(this).attr('id');
var event_id = fullId.split('_');
if(selected_event=="delete"){
jQuery("#row"+event_id[1]).remove();
}
});
The rows get removed for any row that was added in the DOM but the change doesn't get recongized for any new row that I added though my first snippet of jQuery. Any reason why this isn't working how I expect it to?
EDIT: I created a JS fiddle for this. It can be found here: http://jsfiddle.net/Kc5R8/
After you click the Add New Row it loses all of the functionality and doesn't produce an alert when the new drop down box is changed.
Thanks for any advice in advance!
Upvotes: 0
Views: 135
Reputation: 391
You have to bind the on method to a container and then specify the selector.
Have a look at http://jsfiddle.net/ZFGFv/2/
jQuery('table').on('change', '.event_selection' ,function(){
... your code
});
This way, JQuery will listen on the container and watch for every DOM element with .event_selection class.
Upvotes: 1
Reputation: 318312
Try:
$(document).on('change', '.event_selection', function(){
if (this.value == "delete") {
$("#row"+this.id.split('_')[1]).remove();
}
});
Upvotes: 0
Reputation: 4379
I have noticed this behavior as well and have gotten around it by changing the call to ".on" to a ".live"
jQuery('.event_selection').live('change' ,function(){
var selected_event = jQuery(this).val();
var fullId = jQuery(this).attr('id');
var event_id = fullId.split('_');
if(selected_event=="delete"){
jQuery("#row"+event_id[1]).remove();
}
});
Upvotes: 0