1

Trying to get my 1 table row to automatically clone exactly 24 times and then get the "add row +" button to clone additional.

Example can be found here: http://jsfiddle.net/CzZxf/17/

var uniqueIds = $("#math-table tr").length;
$("#button").click(function(){
var $thisRow = $(this).closest("tr"),
$clone = $thisRow.removeClass().clone(),             // Clone row
$inputs = $clone.find("input").val("").removeClass();
uniqueIds++; //Increment ID
$inputs[0].id = "A" + uniqueIds;
$inputs[1].id = "B" + uniqueIds;
$inputs[2].id = "C" + uniqueIds;


$thisRow.after($clone);                    
});
user1040259
  • 6,369
  • 13
  • 44
  • 62

2 Answers2

2

You are misunderstanding .closest, it works similarly to .parents.

I fixed the traversing to find last tr here: http://jsfiddle.net/CzZxf/19/

var $thisRow = $("#math-table tr:last-child")

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • You are right. Thanks! Where would I add the loop code to clone 24 times with my unique IDs on each? – user1040259 Jan 12 '12 at 22:16
  • @user1040259 `var l = 24; while( l-- ) { $("#button").trigger("click" ); }` http://jsfiddle.net/CzZxf/22/ – Esailija Jan 12 '12 at 22:17
  • @user1040259 the code I changed is in the answer :P ( I also pressed "tidy up" in jsfiddle to fix formatting) and the loop is pretty self explanatory – Esailija Jan 12 '12 at 22:24
  • Hi Esailija, Might it be possible to use your example above and not include $("#button").trigger("click"); in the loop? I'd like to turn this into a function and pass different button names to it. Basically the loop doesn't work without a proper name. Maybe I'm confused. Thanks again – user1040259 Jan 13 '12 at 16:29
1

I prefer using templates than using clone. See my DEMO here,

Below addRow function will add a new row to the table.

var rowTmpl = '<tr>' +
         '<td><input type="text" id="A{ID}" name="A" value=""></td>' +
         '<td><input type="text" id="B{ID}" name="B" value=""></td>' +
         '<td><input type="text" id="C{ID}" name="C" readonly="readonly" tabIndex="-1" value=""></td>' +
         '</tr>';

function addRow () {    
    var rowCount = $('#math-table tbody tr').length;

    //modify template
    var addRow = rowTmpl.replace (/{ID}/g, rowCount);

    //append to the tbody
    $('#math-table tbody').append(addRow);
}
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134