tags:

views:

28

answers:

2

Hello all,

I'm using jQuery to dynamically add rows to my HTML table on a button click. For the newly added row, I want to have a '+' and 'X' button for adding/deleting the dynamically added rows.

My HTML for the same is as follows:

<td>  
<button type="button" class="addRow"> +  
</button>
</td>

And my jQuery code for the same is as follows:

$("#table-id").each(function(){
    $("button.addRow", this).live('click', function() {

    var html = '<tr><td> </td> <td> </td> <td> </td> <td> <input type="textbox" name="dateLastContact" class="datesToBeAdded"> </td> ' +  
    '<td> <input type="text" name="newContact"> </td> <td> <input type="text" name="newContactPhone"> </td> ' +
    '<td> <input type="text" name="newContactEmail"> </td> <td> <button class="addRow">+</button> &nbsp; <button class="deleteRow">X</button> </td>  </tr>';  

    var row = $(this).closest('tr'); // get the parent row of the clicked button


    var newRow = $(html).insertAfter(row); // insert content
    /* add datepicker and jQuery UI Button styling to newly added row */
    newRow.find('td').css('text-align','center');
    newRow.find('.datesToBeAdded').datepicker();
    newRow.find('.addRow').button();
    newRow.find('.deleteRow').remove();
    });
});  

But, on adding the new row, I just dont see the 'X' button added next to the '+' row.
Any ideas what I'm doing wrong.

Thanks,
Pritish.

A: 

You are removing the button at the line:

newRow.find('.deleteRow').remove();
cesarnicola
+1  A: 

A few things, your .live() handler can really be .delegate(), like this:

$("#table-id").delegate("button.addRow", "click", function()  {

Then where you're doing this:

newRow.find('.deleteRow').remove();

I think you meant:

newRow.find('.deleteRow').button();

You could combine also that into one statement for both buttons:

newRow.find('.addRowm, .deleteRow').button();

Or if you meant to remove the row when clicked, do this:

newRow.find('.deleteRow').button().click(function() {
  $(this).closest('tr').remove();
});
Nick Craver
The .delegate() did not quite work for me, so I resorted to using .live()
Pritish
@Pritish - It only works in the latest version of jQuery, so if you're on an older version it won't work...hopefully the last bit code in the answer is what you were after.
Nick Craver
@Pritish: again, a later answer is better than mine. This should answer your question fully.
MvanGeest
@Nick : Works perfectly just the way I want, thanks!I'm using jQuery 1.4.1..might try updating to the latest version to see if the .delegate() works.
Pritish