views:

193

answers:

3

So i have this code

$('input.clone').live('click', function(){
   //put jquery this context into a var
   var $btn = $(this);
   //use .closest() to navigate from the buttno to the closest row and clone it
   var $clonedRow = $btn.closest('tr').clone();
   //append the cloned row to end of the table

   //clean ids if you need to
   $clonedRow.find('*').andSelf().filter('[id]').each( function(){
       //clear id or change to something else
       this.id += '_clone';
   });

   //finally append new row to end of table
   $btn.closest('tbody').append( $clonedRow );
});

Problem is, each row i clone gets named whatever _clone How would i write this so that each time i run the function, it picks either a random or more idealy sequential number to append to the id isntead of "_clone"

+1  A: 
String(Math.floor(Math.random()*1000000))

will give you a random number in string form between 0 and 999999.

Amber
+1  A: 

Why not use the count of rows in the table

$clonedRow.find('*').andSelf().filter('[id]').each( function(){
       //clear id or change to something else
       var rowCount = $btn.closest('tr').siblings().length;
       this.id += 'row_' + rowCount;
   });
redsquare
A: 
$('input.clone').live('click', function(){
   var $btn = $(this);
   var $clonedRow = $btn.closest('tr').clone();

   $clonedRow.find('*').andSelf().filter('[id]').each( function(){
       this.id += '_clone' + $(this).siblings().size();
   });

   //finally append new row to end of table
   $btn.closest('tbody').append( $clonedRow );
});
Peter Kaleta
same as mine + size() is slower than .length (size() actually calls .length internally)
redsquare