Delete tr table html jquery

1

I'm trying to create a button to add a tr to an existing table, but I have not yet succeeded.

I used the following code to add tr, this works normally:

HTML

<table id="Table">
<tbody>
    <tr>
        <th>A</th>
        <th>B</th>
        <th>C</th>
        <th>D</th>
    </tr>
    <tr style="background:white">
    <td>Item1</td>
    <td>Item2</td>
    <td>Item3</td>
    <td><input type="button" class="Remover" value="x" style="background:red;"></td>
    </tr>
</tbody>

JavaScript

$('#Table').click(function(){
    var conta = 0;
    var dados = [$('#Item1').val(),$('#Item2').val(),$('#Item3').val(),$('#Item4').val()];
    var cols = '<tr style="background:white">';
    for(var i=0; i < 8; ++i){           
        if(dados[i] == ""){
            conta=1;
            } else{
            cols += '<td>'+dados[i]+'</td>';    
            }
    };
    if(conta==0){
    cols += '<td><input type=\"button\" id=\"Remover\" value="x" style=\"background:red;\" /></td>';
    cols += '</tr>';
    $("#InserirPedido tbody").append(cols);
    return false;
    }else{
        alert('Preencha todos os campos');
        return false;
    }
});

I tried to use the following code to remove, but without success:

$('#Remover').click(function () {
     $(this).closest('tr');
});
    
asked by anonymous 15.05.2015 / 13:17

2 answers

2

You have two problems. One is that you can not have duplicate IDs, the other is that the event dropper is not added to HTML that does not yet exist, you have to use delegation.

Use classes in this HTML that you add:

cols += '<td><input type=\"button\" class=\"remover\" value="x" style=\"background:red;\" /></td>';

and then use delegation like this:

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

You can read more about delegation here .

    
15.05.2015 / 13:20
2

cols += '<td><input type=\"button\" class=\"remover-linha\" value="x" style=\"background:red;\" /></td>';

Then you can create a jQuery function.

$('#Table').on('click', '.remover-linha', function(){
    $(this).closest('tr').fadeOut(300);
});

Because objects are dynamically created, On should be used.

    
15.05.2015 / 13:27