Reputation: 525
My form has two fields are short description and long description initially the form fileds names are section[new][1][description] and section[new][1][ldescription]
I would like to generate clone form fields which generate names like section[new][2][description] and section[new][2][ldescription]. each time i clone new form it should generate form fields names with increment id in between like section[new][incrementid goes here][description]
How to achieve this using regex or any other jquery techniques?
Here is code i'm using for form clonning
jQuery("button.add").on("click", clone);
function clone(){
var clone = jQuery(this).parents(".pbone_section_default").clone()
.appendTo("#section_list")
.attr("id", "pbone_section_default_" + cloneIndex)
.find("*")
.each(function() {
// here we can put any logic to achieve desire element name
this.name = logic goes here;
})
.on('click','button.delete',remove);
};
Upvotes: 0
Views: 80
Reputation: 2967
Yes it can be done (you were close).. Assuming you are using a 0 based indexing (i.e. starting from section[new][0][description]
), try this code:
function clone(){
var $clone = $(".pbone_section_default").last(),
index = $clone.index();
$clone.clone()
.appendTo("#section_list")
.find("[name*='["+index+"]']")
.each(function(){
$(this).attr("name", $(this).attr("name").replace("["+ index +"]", "["+ parseInt(index+1) +"]"));
});
};
see a working example here: FIDDLE
Anyway, i suggest you to use templating engine instead, like Mustache or Underscore.. but there are plenty of them.. check this article and see which suits better to your projet
Upvotes: 3
Reputation: 7878
You can use .match()
and .replace()
to find the number in the string an increment it:
.each(function() {
this.name = incrementNumberinString(this.name);
});
var incrementNumberinString = function (string){
var i = parseInt(string.match(/\d{1}/g))+1;
return string.replace(/\d{1}/g, i)
}
The regex will find any digit which is existing exactly 1 times.
See here for an example of the Regex.
Note: This will only work under the assumption that there is only 1 number inside your inputs name.
Upvotes: 2