why is jquery first().clone() in a table still cloning multiple elements?

I am trying to duplicate a table row and append to my table based on user entry of 1 to 10. Based on the input, I would like to append that many rows to my table.. Here is my current for loop. When I run this code and test, jQuery is cloning an exponential number of rows and appending. Any help would be appreciated!

$(".RosterCountSelect").change(function(){
   var numOfPlayers = this.value;
   for (var i = 0; i < numOfPlayers; i++){
       $(".PlayerRow").clone().first().insertAfter(".PlayerRow");
   }
});     

And here is the HTML markup.

 <form id="PlayerInfo">
  <table>
   <tr class = "PlayerRow">
    <td><input class="teamInput" type="text" placeholder="Player Full Name" /></td>
    <td><input class="teamInput" type="text" placeholder="Player Number" /></td>
    <td>? ?<input class="teamInput" type="text" placeholder="Jersey Size" /></td>
    <td>? ??<input class="teamInput" type="text" placeholder="Short Size" /></td>
    <td>??<input class="teamInput" type="text" placeholder="Male/Female" /></td>
   </tr>
  </table>
 </form>

Answers 1

  • The duplication is due to .insertAfter() when you provide an argument that matches multiple elements.

    In that case, it will .clone() again in order to insert your clone after each of matched elements.

    1 intended clone * 5 existing rows = 5 new clones inserted

    You'll want to modify the selector to match only one element to insert after, e.g. with :last:

    $(".PlayerRow").clone().first().insertAfter(".PlayerRow:last");
    

    Also, though it doesn't contribute to the duplication, the order you have .clone() and .first() being called is wasteful. It creates clones of every existing row, then discards all but the first.

    It's more efficient to reduce the size of the collection before cloning:

    $(".PlayerRow").first().clone().insertAfter(".PlayerRow:last");
    

Related Articles