I've been going through my dynamically added code and changing everything that was using .click() to use .on("click") and its been working great but now I've run into something that I am not sure how to convert to dynamically added compatible.
Here is the code: This is a function in javascript that is called when a button named "Add" or "Remove" is clicked (these buttons are also dynamically added after another button is clicked)
function row_add_remove(sname, snum, count, type) {
if (type == "add") {
var selectbox = '<select id="qty_'+snum+'_'+count+'" name="qty_'+snum+'_'+count+'">';
for (i=1;i<16;i++){selectbox += '<option value='+i+'>'+i+'</option>';}
selectbox += '</select>';
if (count > 1) {
$("#tr_"+sname+"_"+(count-1)).after('<tr id="tr_'+sname+'_'+count+'"><td>'+selectbox+' X <input type=text id="item_'+sname+'_'+count+'" name="item_'+snum+'_'+count+'" size="70" placeholder="Item '+count+'" /></td></tr>');
$("#toprow"+snum+"_count").html("("+count+")");
}
}
if (type == "remove") {
if (count == 1) {
$("#"+sname).hide();
$("#toprow"+snum+"_count").html("");
$("#td_"+sname+"_"+count).remove();
$("#ph_order_div").show();
count--;
}
if (count > 1) {
$("#tr_"+sname+"_"+count).remove();
count--;
$("#toprow"+snum+"_count").html("("+count+")");
}
if (count < 0) {count = 0;}
}
}
The problem (I think, maybe its more than this) is the .after() doesn't fire. Now i'm not sure if the problem lies with that or with the whole code but when I click the Add button its not adding another TR after the one that is shown by default.
This code works great when NOT dynamically added so can anyone help me with what I need to change to get the above function to work when the buttons that call it and the TR's that it tries to modify are dynamically added?
Here is the code that is fired when the buttons are clicked:
whatmeatfield = $("#meat_field_count").html();
$(document).on("click", "#add_btn_1", function() {
if (whatmeatfield <= 0) {whatmeatfield = 1;}
whatmeatfield++;
row_add_remove("meatseafood",1,whatmeatfield,"add");
});
$(document).on("click", "#remove_btn_1", function() {
row_add_remove("meatseafood",1,whatmeatfield,"remove");
whatmeatfield--;
if (whatmeatfield <=0) {whatmeatfield = 1;}
});