添加/删除输入字段

时间:2014-01-20 19:53:32

标签: javascript jquery

我有一个我正在忽视的愚蠢的虫子。我可以通过单击加号按钮向表单添加项目,但是我无法删除已添加的项目。这是我的代码:

    <script>
    $(document).ready(function(){
        var item_index=0;

        $("#add_additional_item").click(function(){

            item_index++;
            $("#Additional_item").attr("placeholder", "Additional Item " + item_index);
            $("#Additional_items_wrap p").attr("id", "remove_additional_item" + item_index);
            $("#number_of_fields").attr("value", item_index);

$(this).parent().before($("#Additional_items_wrap").clone().attr("id","Additional_items_wrap" + item_index));
            $("#Additional_items_wrap" + item_index).css("display","inline");

            $("#Additional_items_wrap" + item_index + " :input").each(function(){
                $(this).attr("name",$(this).attr("name") + item_index);
                $(this).attr("id",$(this).attr("id") + item_index);

            }); 

            $("#remove_additional_item" + item_index).click(function(){

                $(this).closest("div").remove();
                item_index--;
            });
        });
    });
</script>

HTML:

            <label>Add Additional Item:</label> 
        <input type="hidden" id="number_of_fields" name="number_of_fields">                           

        <div id="Additional_items_wrap" class="hidden">

            <input type="text" name="Additional_item" id="Additional_item">
            <p class="icon-minus" id="remove_additional_item"></p>

        </div>

        <div id="input_add_item">

            <p id="add_additional_item" class="icon-plus" style="float:right; cursor:pointer"></p> 

        </div> 

1 个答案:

答案 0 :(得分:1)

您正在尝试将jQuery与动态html一起使用,请参阅此处:

“原因是您无法将处理程序绑定到DOM中当前不存在的项目” jquery click event not working for dynamic fields

更新: 这是我的意思的一个例子。

$(document).on("click", "#remove_additional_item" + item_index, function () {
  alert ("You just hit the jackpot!");
});