Delete tr table html jquery

Asked

Viewed 5,211 times

1

Guys, I created a routine that adds a tr to an existing table, and I’m trying to create a boot to remove this tr, but I haven’t been able to.

I used the following code to add to 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 to no avail:

$('#Remover').click(function () {
     $(this).closest('tr');
});
  • Don’t change the question. Leave it as it was or the answers will get wrong. Note that I used a class with R small. Example: http://jsfiddle.net/0686n0qy/

  • ops...sorry Sergio

2 answers

3

Something you can do is put class in place of ID 'remove'.

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);
});

As objects are created dynamically, On should be used.

2


You have two problems. One is that you can’t have duplicate Ids, the other is that the event receiver is not added to HTML that doesn’t exist yet, you have to use delegation.

Use classes in this HTML you add:

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

and then uses delegation like this:

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

You can read more here about delegation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.