jquery clone form fields and increment id

前端 未结 4 2228
抹茶落季
抹茶落季 2020-11-27 03:37

I have a block of form elements which I would like to clone and increment their ID\'s using jQuery clone method. I have tried a number of examples but a lot of them only clo

4条回答
  •  星月不相逢
    2020-11-27 04:13

    HTML

    JavaScript - Jquery v1.7 and earlier

    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    
    $("button.clone").live("click", function(){
        $(this).parents(".clonedInput").clone()
            .appendTo("body")
            .attr("id", "clonedInput" +  cloneIndex)
            .find("*").each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = match[1] + (cloneIndex);
                }
        });
        cloneIndex++;
    });
    

    There is only one silly part :) .attr("id", "clonedInput" + $(".clonedInput").length) but it works ;)

    JAvascript - JQuery recent (supporting .on())

    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    
    function clone(){
        $(this).parents(".clonedInput").clone()
            .appendTo("body")
            .attr("id", "clonedInput" +  cloneIndex)
            .find("*")
            .each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = match[1] + (cloneIndex);
                }
            })
            .on('click', 'button.clone', clone)
            .on('click', 'button.remove', remove);
        cloneIndex++;
    }
    function remove(){
        $(this).parents(".clonedInput").remove();
    }
    $("button.clone").on("click", clone);
    
    $("button.remove").on("click", remove);
    

    working example here

提交回复
热议问题