views:

164

answers:

3

Hi

I have problems with my keyup binding when cloning an element. Here's the scenario:

I have an html markup like this:

<tr class="rijbasis">
   <td>
      <input type="text" class="count" />
   </td>
   <td>
       <span class="cost">10</span>
   </td>
   <td>
       <span class="total">10</span>
   </td>
</tr>

I'm binding an keyup function to the input element of my table row like this:

$('.rijbasis input').keyup(function(){
    var parent = $(this).parent().parent();
     $('.total',parent).text(parseInt($('.cost',parent).text()) * parseInt($('.count',parent).val()));
}

I designed the function like this so I could clone the table row on a onclick event and append it to the tbody:

$('.lineadd').click(function(){
        $('.contract tbody').append($('.contract tbody tr:last').clone());
        $('.contract tbody tr:last input').val("0");
 });

This al works , but the keyup function doesnt work on the input elements of the cloned row..

Can anybody help or advice? I hope I was clear enough and I'll be surely adding details if needed to solve this problem.

Greetings

+1  A: 

Use .live instead of .keyup

Plynx
+3  A: 

You've got two real options

  • use clone(true) which will also clone the bound event handlers
  • use event delegation with live() so that the event handler is bound to a parent element and thus newly added rows will get the same functionality
Russ Cam
Cool, did not know that! Use this one then if you're only going to clone, I think it will perform better than .live.
Plynx
thx for your quick answer :)
Sam Vloeberghs
no probs, happy to help :)
Russ Cam
+1  A: 

Use jQuery's live events; this way the handler will automatically be bound to newly created elements (such as the clones in your example).

For example:

$('.rijbasis input').live('keyup', function()
{
    var parent = $(this).parent().parent();
    $('.total',parent).text(parseInt($('.cost',parent).text()) * parseInt($('.count',parent).val()));
}
Will Vousden
I had a semi-related problem that shared the same basis of this answer. Thanks so much!
kevtrout