I can’t remove cloned lines

Asked

Viewed 35 times

1

I’m trying to create a dynamic form, I’m able to clone normally, but I can’t delete the cloned items. What’s wrong with my code? In that case, with a double click on the cloned "TR" you would have to delete the line, but it does not work on cloned items.

$(document).ready(function() {
    $(".clon").click(function() {
        $(".clonar").clone()
            .appendTo(".lista")
            .attr("class", "clonado")
            .find("input").removeAttr("id");
    });
});
$(document).ready(function() {
    $(".clonado").dblclick(function() {
        $(this).remove();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form name="form1">
    <table>
        <tr class="clonar">
            <td>
                <input type="text" name="cod[]" id="cod" value="">
            </td>
            <td>
                <input type="text" name="prod[]" id="prod" value="">
            </td>
            <td>
                <input type="text" name="vlr[]" id="vlr" value="">
            </td>
        </tr>
        <tr>
            <td>
                <input class="clon" type="button" name="clonar" value="Clonar">
            </td>
        </tr>
    </table>
</form>
<form name="form2">
    <table class="lista">

    </table>
</form>

1 answer

1


The problem is that this line:

$(".clonado").dblclick(function(){
    $(this).remove();
});

will add an event headphone to the elements that exist at that time and not to future elements.

To solve this you have two possibilities:

You can add a new event headphone to the cloned element like this:

$(".clonar").clone()
  .dblclick(function(){ $(this).remove(); }) // <------  
  .appendTo(".lista")
  .attr("class","clonado")
  .find("input").removeAttr("id");

Or use delegation to search for elements that are added later:

$('form[name="form1"] table').on("dblclick", ".clonado", function(){
    $(this).remove();
});

Browser other questions tagged

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