0

i am in touch with jquery for the first time and ran into this: I am trying to create a dynamic input-form. A click function creates a new list-item with another click function nested into it (to provide a remove function for the clicked item).

When i execute the nested click function it appears to be called the number of instances that have been created of it.

Here is the code (i tried to remove as much as possible, but i am not quite sure where the error is - so i guess i left to much stuff in - sorry).

$("#addIngredient").click(function(e){
    e.preventDefault();

    var prefix = "form-"
    var last = $("#IngredientForm ul li").last().html();

    $("#IngredientForm ul").append("<li>"+last+"</li>");

    var name = $("#IngredientForm ul li:last input").attr("name");
    name = name.replace(prefix,'');
    var count = parseInt(name[0]);
    count += 1;


    $("#IngredientForm ul li:last input").attr("name",prefix+count+"-weight")
    $("#IngredientForm ul li:last select").attr("name",prefix+count+"-ingredient")
    $("#IngredientForm ul li:last input").attr("id","id_"+prefix+count+"-weight")
    $("#IngredientForm ul li:last select").attr("id","id_"+prefix+count+"-ingredient")
    $("#id_form-TOTAL_FORMS").val(count+1);

    $(".deleteIngredient").click(function(e){
        e.preventDefault();

        var aktuell = $(this).closest('li');
        var formCount;
        name = aktuell.children('input').attr("name");
        name = name.replace(prefix,'');
        counter = name.replace("-weight",'');
        formCount = parseInt($("#id_form-TOTAL_FORMS").val());

        aktuell.remove();
        --formCount;

        $("#id_form-TOTAL_FORMS").val(formCount);
        for (var i = parseInt(counter); i<formCount; i++){
        var newName = "form-"+(i);
        $("#id_form-"+(i+1)+"-weight").attr("name",newName+"-weight");
        $("#id_form-"+(i+1)+"-ingredient").attr("name",newName+"-ingredient");
        }

    });

 });

4 Answers4

2

This block

$(".deleteIngredient").click(function(e){...

attaches a clickevent to all .deleteIngredient elements, also those created before.

You have to put this block outsite the click event of #addIngredient. You can make the delete event to be attached also to every element added in the future.

$("#addIngredient").click(function(e){
    // ...
});

$(document).on("click", ".deleteIngredient", function(e){
    // ...
});
Markus Kottländer
  • 7,580
  • 3
  • 32
  • 58
  • Yes this will probably work fine too, since the event handler seems to find it's parent `
  • ` and work from that.
  • – Pointy Jan 08 '14 at 21:30