jonal
jonal

Reputation: 75

jquery functions after append row to table

I need some help so I hope you could help me. I have a table which rows are added this way after click on a button.

var row = "<tr><td><input class='check_box' type='checkbox'></input>some text<td></tr>";

$('#pl_table').append(row);

I also have jquery function that adds a class to a row when checkbox is selected. So this class has a .css definition for background color.

$('input:checkbox').on('change', function() { 
    if(this.checked) {
        $(this).closest('tr').addClass('selected');
    }
    else{
        $(this).closest('tr').removeClass('selected');
    }
}

The problem is on('change') event is not called for rows added. And it is called for rows that already exist when loading the page.

why does this happend? What is wrong on my code? Thank you for your help.

Upvotes: 2

Views: 1467

Answers (5)

EnflowSoft India
EnflowSoft India

Reputation: 1

As of jQuery 1.4, .after() supports passing a function that returns the elements to insert. Refer this link.

Upvotes: 0

jonal
jonal

Reputation: 75

I'ts much better to use:

$(document).on('change','#elemnt',function(){
     //do something here
});

So there's no need to call BindDynamicEvents(); every time a new row is added.

Upvotes: 0

kizisoft
kizisoft

Reputation: 386

If you want to keep the current syntax try this:

    $('#pl_table').on('change', 'input:checkbox', function () {
        if (this.checked) {
            $(this).closest('tr').addClass('selected');
        }
        else {
            $(this).closest('tr').removeClass('selected');
        };

This way you don't add event on each input, you only add it on the table and fire it when input is changed. I prefer this for dynamical generated elements.

Upvotes: 1

Vim
Vim

Reputation: 559

I have faced the same situation and the steps I followed to solve this are given below,

a. Put $('input:checkbox').on('change' inside a method as shown below,

function BindDynamicEvents()
{
   $('input:checkbox').off('change').on('change', function() { 
    if(this.checked) {
        $(this).closest('tr').addClass('selected');
    }
    else{
        $(this).closest('tr').removeClass('selected');
    }
}
}

b. Call this method after the $('#pl_table').append(row) as shown below,

$('#pl_table').append(row);
BindDynamicEvents();

This will solve the problem.

Note: please include .off('change') as shown in code to avoid the event being fired multiple times.

Upvotes: 1

hamed
hamed

Reputation: 8043

Try this:

var row = "<tr><td><input class='check_box' type='checkbox' onchange="change(this);"></input>some text<td></tr>";

$('#pl_table').append(row);


function change(element)
{
    if(element.checked) {
        element.closest('tr').addClass('selected');
     }
  else{
    element.closest('tr').removeClass('selected');
   }
}

Upvotes: 0

Related Questions