0

Hi I am using jQuery to highlight a row on click. It is working fine on page 1 but when I navigate to next page below mentioned code is not working.

Table is being rendered dynamically.

Below is my code snippet

$('table tr').slice(1).each(function(a,b){
                                $(b).click(function(){
                                     $('table tr').css('background','#ffffff');
                                     $(this).css('background','red');   
                                }); 
                            });

any help is welcome

user_xyz.LOL
  • 337
  • 1
  • 4
  • 14
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Nov 08 '19 at 12:08

2 Answers2

1

It's probably because the table is regenerated and your code only set the event handlers 1 time for the first page.

I'd recommend to use a class on the closest static parent of the table and table row so you can do easy event delegation like follow:

$('.closestStaticParent').on('click', '.tableRow', function(){...});
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73
  • 1
    @user_xyz.LOL Your welcome, if one of the answers answers your question then please accept the answer that fits you best (check mark left of the answers). This way people can see you don't need help anymore. – Mark Baijens Nov 08 '19 at 15:54
1

Use the three-argument form of handling events. It also applies to elements added later dynamically.

$(document).on('click', 'table tr', function(){
     $('table tr').css('background','#ffffff');
     $(this).css('background','red');   
});
Adder
  • 5,708
  • 1
  • 28
  • 56
  • worked and thanks for reply. But this also highlights the header, thats why I sliced first element from list – user_xyz.LOL Nov 08 '19 at 13:22
  • Assuming you have `th` tags in the header, you can omit the header row by by checking `$(this).find('td').length>0` – Adder Nov 08 '19 at 13:25