You can try something like this:
$("a").click(function() { $("div.input.text") .last() .clone() .appendTo($("body")) .find("input").attr("name",function(i,oldVal) { return oldVal.replace(/\[(\d+)\]/,function(_,m){ return "[" + (+m + 1) + "]"; }); }); return false; });
As shown here: http://jsfiddle.net/6Xg4S/
Essentially, when you click on your anchor, it clones the last div and adds it to the body (at least my example joins the body - obviously, you could add it to something more specific or .insertAfter()
last), then take the number from the middle of the name and increase it by replacing the regular expression.
Having done this, I would like to note that you do not need to specify your unique names: all server technologies that I would like to use can process several request parameters with the same name (for example, Java has getParameterValues()
that returns an array).
EDIT: Here's the version that clones only the input element, in particular the last entry in the div, updates its identifier and adds it to the end of the div. According to your comment, this no longer changes the name (although, obviously, you can simply add an extra .attr()
call as above if you want to change the name too). Oh, and also this sets the value to empty (I forgot to do it higher).
$("#extra a").click(function() { var $div = $(this).next(); $div.find("input") .last() .clone() .appendTo($div.append("<br/>")) .val("") .attr("id",function(i,oldVal) { return oldVal.replace(/\d+/,function(m){ return (+m + 1); }); }); return false; });
Demo: http://jsfiddle.net/6Xg4S/4/