开发者

Use jQuery clone to copy only 1 row with classname

开发者 https://www.devze.com 2023-02-25 04:10 出处:网络
I\'ve been struggling with this for two days! From a suggestion in SO, I put the add button in the table footer. When it\'s clicked for the first time, it adds one new row, which is what I want. The s

I've been struggling with this for two days! From a suggestion in SO, I put the add button in the table footer. When it's clicked for the first time, it adds one new row, which is what I want. The second time, however, it adds two new rows; the third time, four new rows; the fourth time, eight new rows! It gets worse and worse!

This code is for adding members to a database. The first row is the member's own information. The other rows are for the user to add other members to their group. So it's the second or later rows that I want to clone. The new rows should be added at the end.

The tr to be copied has a class of .leaderrow. I think the jQuery is copying all of the rows with that class each time, instead of just one. How can I get it to add just the one row each time the button is clicked?

Here's the jQuery:

$(document).ready(function(){
    $('#addRow').live('click', function() {
        $('.leaderrow').clone().appendTo('#entries');
    });
})

Here's the table, which is part of a form:

<table width="100%" border="0" class="unsorted_table">
  <thead>   
      <tr>
           <th>Name*</th>
           <th>Action</th>
      </tr>
  </thead>
  <tbody id="entries">
   开发者_如何学Python   <tr>
            <td>User's own name</td>
            <td>&nbsp;</td>
      </tr>
      <tr class="leaderrow">
            <td><select name="leaderid[]" >
              <option value="3">Sue</option>
              <option value="4">Jeannie</option>
              <option value="5">Kerry</option>
              <option value="6">Travis</option>
               </select>
            </td>
            <td><a href="" name="delete_row[]" class="remove">remove</a></td>
       </tr>
    </tbody>
    <tfoot>
       <tr> 
            <td><p><input type="button" id="addRow" value="Add Another" /></p></td>
       </tr>
    </tfoot>
</table>


First of all $('.leaderrow') selects all elements that match that class. You could use .first(), .last() or .eq() to select a specific one.

I however would suggest that you add a HIDDEN .leaderrow.template (has both classes) that is cloned, then .removeClass('templaterow') before appending.

Also, if you are dealing with more than one table, you might want to do something with .closest() to restrict the area you are searching:

var tmpl = $(this).closest('table').find('.leaderrow.template');
tmpl.clone().removeClass('template').insertBefore(tmpl);
// and use CSS:
// .leaderrow.template { display: none; }
0

精彩评论

暂无评论...
验证码 换一张
取 消