I can not remove cloned lines

1

I'm trying to create a dynamic form, I'm able to clone normally, but I can not delete the cloned items. What's wrong with my code? In that case, double clicking on the cloned "TR" 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><formname="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>
    
asked by anonymous 26.07.2016 / 05:52

1 answer

1

The problem is that this line:

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

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

To solve this you have two possibilities:

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

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

Or you use delegation to look for elements that are added later:

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