How to remove dynamically generated table row with JQuery?

3

I'd like one of the automatically generated columns in the table to have a function to delete the row, but the on click is not working. How should I do this?

$(document).ready(function(){ 
            $("#associar1").on("click", function(e){        
     var coluna = "<tr>";
                             coluna += "<td width='40%'  align='center'><input type='text' disabled = 'disabled'   value= "+$("#canal").val()+" name='vigenciaCanalVendaVO.canalVendaVO.codigo'/></td>";
                             coluna +="<td width='40%'  align='center'><input type='text'  mask = '99/99/9999' disabled = 'disabled' data-mask='data' data-date-type='default' size='12' maxlength='10'  value="+$("#dataInicioVigencia").val()+" name='vigenciaCanalVendaVO.dataInicioVigenciaAssociacaoPlano'/>"
                             coluna +="At&eacute;<input type='text' mask='99/99/9999'  data-mask='data' disabled = 'disabled' data-date-type='default' size='12' maxlength='10'  value="+$("#dataFimVigencia").val()+" name='vigenciaCanalVendaVO.dataFimVigenciaAssociacaoPlano'/></td>";
                             coluna +="<td align='center'><img src='/includes/images/bt_remover.gif' id='remover' style='cursor:pointer;cursor:hand;'/></td>";
                             coluna += "</tr>";               
                             //alert(coluna);    
                        ($('#tabelaCanais')).append(coluna);
                    });
    });
    $("#remover").on("click",function(e){
        $(this).parent().parent().remove();
    });
    
asked by anonymous 22.10.2014 / 14:31

1 answer

5

You have to delegate this event because this #remover element is inserted after jQuery has been read. I explained this delegation question in this answer .

You can do this:

$("#tabelaCanais").on("click", "#remover", function(e){

I also suggest changing this ID to class, otherwise the jQuery will only find the first #remover and will not work in the others. So the code I suggest is:

$("#tabelaCanais").on("click", ".remover", function(e){
    $(this).closest('tr').remove(); 
});

and HTML:

<img src='/includes/images/bt_remover.gif' class='remover' style='cursor:pointer;cursor:hand;'/>

Note: I use closest () since it is more reliable than .parent().parent() if you have more elements in the DOM between image and the line.

    
22.10.2014 / 14:42