From 8118a45953d02d84e4bf6aa6a3ed40dfea910bec Mon Sep 17 00:00:00 2001 From: nathanvda Date: Sat, 13 Oct 2012 00:11:16 +0200 Subject: [PATCH] Make sure we handle self-nested forms correctly. Fixes #96 and #74. --- app/assets/javascripts/cocoon.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/app/assets/javascripts/cocoon.js b/app/assets/javascripts/cocoon.js index 2169599..2418e6f 100644 --- a/app/assets/javascripts/cocoon.js +++ b/app/assets/javascripts/cocoon.js @@ -1,5 +1,7 @@ (function($) { + var cocoon_element_counter = 0; + function replace_in_content(content, regexp_str, with_str) { reg_exp = new RegExp(regexp_str); content.replace(reg_exp, with_str); @@ -22,20 +24,20 @@ insertionMethod = $this.data('association-insertion-method') || $this.data('association-insertion-position') || 'before'; insertionNode = $this.data('association-insertion-node'), insertionTraversal = $this.data('association-insertion-traversal'), - regexp_braced = new RegExp('\\[new_' + assoc + '\\]', 'g'), - regexp_underscord = new RegExp('_new_' + assoc + '_', 'g'), - new_id = new Date().getTime(), + regexp_braced = new RegExp('\\[new_' + assoc + '\\](.*?\\s)', 'g'), + regexp_underscord = new RegExp('_new_' + assoc + '_(\\w*)', 'g'), + new_id = new Date().getTime() + cocoon_element_counter++, newcontent_braced = '[' + new_id + ']', newcontent_underscord = '_' + new_id + '_', - new_content = content.replace(regexp_braced, '[' + new_id + ']'); + new_content = content.replace(regexp_braced, '[' + new_id + ']$1'); if (new_content == content) { - regexp_braced = new RegExp('\\[new_' + assocs + '\\]', 'g'); - regexp_underscord = new RegExp('_new_' + assocs + '_', 'g'); - new_content = content.replace(regexp_braced, '[' + new_id + ']'); + regexp_braced = new RegExp('\\[new_' + assocs + '\\](.*?\\s)', 'g'); + regexp_underscord = new RegExp('_new_' + assocs + '_(\\w*)', 'g'); + new_content = content.replace(regexp_braced, '[' + new_id + ']$1'); } - new_content = new_content.replace(regexp_underscord, newcontent_underscord); + new_content = new_content.replace(regexp_underscord, newcontent_underscord + "$1"); if (insertionNode){ if (insertionTraversal){