Search code examples
javascriptjqueryhtml

Properly renaming cloned inputs JQuery


I'm attempting to craft my own cloning function that changes the name of cloned inputs so they can be collected by PHP.

on W3C I found this simple function to build from

$("button").click(function(){
    $("p").clone().appendTo("body");
});

I modified it to clone a fieldset with multiple inputs and it worked. I took it a step farther to try to make it rename and integer the name attribute of the different input elements and now it doesn't even clone the field.

Here's what I have so far.

$("#p20_01_yes").click(function(){
    var num     = $('.clonedInput').length,
    newNum  = new Number(num + 1);
    $("#cloner").clone($("input, textarea, select").each().attr('name'+newNum)).appendTo("#page20");
});

I just tried to post a snippet of the HTML but I got a warning telling me the limit is 30,000 characters so here's a js fiddle that shows everything.

https://jsfiddle.net/Optiq/krjztsm2/

I structured the JQuery the way I did because I figured it would be more appropriate to do the renaming inside of the clone function then append the results to the page rather than appending it then going back and separating it from everything else to dig back through... figured that would make more sense to the computer. Is this the right way to look at it?


Solution

  • You were pretty close already. I'm not sure if my answer will work perfectly (seeing that the JSFiddle is pretty messy), but you could just adapt the classes and ids afterwards.

    You just need to split your tasks into two parts:

    1. Clone the fieldset
    2. Update the input elements names (and possibly ids as well?)

    Here is an example of how this could work:

    $("#p20_01_yes").click(function(){
        var num = $('.clonedInput').length,
        newNum = new Number(num + 1);
        var $clonedFieldset = $("#cloner").clone().appendTo("#page20");
        $clonedFieldset.find("input, textarea, select ").each(function() {
            var $item = $(this);
            $item.attr('name', $item.attr('name') + newNum);
        });
    });