birdy
birdy

Reputation: 9646

All checkbox columns are not selected for row that is added to the dom

I have a grid to which I can dynamically add rows and columns. Each column has a checkbox next to it and checking it makes all checkboxes for that column be selected.

It looks like this:

enter image description here

Below is my code to add columns by clicking the "Add another column" button.

$('#btnAddCol').click(function () {
    myfrom.find('tr').each(function(){
        var trow = $(this);
        var columnName = $('#colorName').val()
        if(trow.index() === 1){
          trow.append('<th > ' + columnName + ' <input type="checkbox" class="colmaster"/>');
        }else if (trow.index() > 1){
            trow.append('<td><input type="checkbox" name="'+columnName+'" class="child" /></td>');
        }
    });
    iter += 1;
});

And here is the code for selecting all checkboxes in the column.

$('.colmaster').click(function(){
 var idx = $(this).parent().index();
 $('#colorgrid td:nth-child(' + (idx + 1) + ') input.child').prop('checked', this.checked);
})

Question For the newly added columns, justadded in the screenshot above, when I check the checkbox it doesn't seem to select all checkboxes in that column

Here is a working fiddle for everything: http://jsfiddle.net/y55nn1qx/4/

Upvotes: 2

Views: 90

Answers (2)

PeterKA
PeterKA

Reputation: 24648

Change $('.colmaster').click(function(){ to:

$('.colmaster').live('click', function(){ // jQuery < 1.7

So that any .colmaster added to the DOM after DOM ready can also be included.

NOTE

If you upgrade to a modern version of jQuery you would use:

$(document).on('click', '.colmaster', function(){ //jQuery 1.7+

jQuery API Documentation | live

Upvotes: 1

tckmn
tckmn

Reputation: 59333

$('.colmaster').click will only bind the event to .colmaster elements that exist at the time of running the code. Try something like this:

$('#colorgrid').on('click', '.colmaster', function() {
     // insert your .colmaster.click code here
});

Here's the jQuery API reference for on.

Upvotes: 3

Related Questions