Cloning last three rows and incrementing multidimensional input names?
Having a hard time figuring this one out...
I am attempting to clone the last three rows of a table while also incrementing the names of the inputs, which are arrays.
(I've put the code on jsfiddle http://jsfiddle.net/5ntbg/1/
To be clear, once the user clicks the "newissue" button, the following should happen:
(1) The last three rows of the button's parent table (i.e., table.subtitle-form) are cloned and appended to the table.subtitle-form
(2) The names of the inputs should be incremented appropriately:
- title[0][subtitle][0]
is cloned as
- title[0][subtitle][1]
and
- title[0][subtext][0]
is cloned as
- title[0][subtext][1]
(I have the parent table cloning working as seen at the fiddle link, it's just the inner table that I'm having an issue with...)
(code also posted below)
- <div class="ttables">
- <table cellspacing="0" cellpadding="0" class="title-form">
- <thead>
- <tr><th><label>Title</label></th></tr>
- </thead>
- <tbody>
- <tr><td><input type="title" class="form-text" value="" name="title[0]"></td></tr>
- <tr class="subtitle-container"><td>
- <table cellspacing="0" cellpadding="0" class="subtitle-form">
- <tbody>
-
- <tr><td><label>Subtitle</label><input type="subtitle" class="form-text" value="" name="title[0][subtitle][0]"></td></tr>
- <tr><td><label>Subtext</label><textarea class="form-textarea subtext" name="title[0][subtext][0]"></textarea></td></tr>
- <tr class="rowspacer"><td></td></tr>
-
- </tbody>
- <tfoot>
- <tr><td><button class="faux-button" id="newsubtitle">Add subtitle</button></td></tr>
- </tfoot>
- </table>
- </td></tr>
- </tbody>
-
- <tfoot>
- <tr><td><button class="faux-button" id="newtitle">Add title</button></td></tr>
- </tfoot>
- </table>
- </div>
- //js
- $('#newsubtitle').live('click', function(e) {
- e.preventDefault();
-
- var numrows = $(this).closest('table').find(' tbody > tr').length;
-
- $(this).closest('table').find(' tbody > tr:gt('+ (numrows-3) +')')
- .clone()
- .find(':input')
- .each(function() {
- this.name = this.name.replace(/\[(\d+)\]/, function(str,p1){
- return '[' + (parseInt(p1,10)+1) + ']';
- });
- })
- .end()
- .appendTo($(this).closest('table > tbody'))
- });
-
- $('#newtitle').live('click', function(e) {
- e.preventDefault();
- var numtable = $('table.title-form').length;
- $('table.title-form:first')
- .clone()
- .find(':input')
- .each(function() {
- this.name = this.name.replace(/\[(\d+)\]/, function(str,p1){
- return '[' + (parseInt(p1,10)+1) + ']';
- });
- })
- .end()
- .appendTo('.ttables')
- });