0

Hey I am trying to get the row of data from a generated html table, I added buttons to the table and I am trying to figure out how to add events to the buttons in order to grab a few cells from that row.

My code does not seem to work and I have no idea why.

I tried following this jsfiddle example, but no luck... jsFiddle example Here is my Code.

Generate table rows with buttons:

function buildHtmlTable(CompanyTime) {
            $("#excelDataTable").empty();
            var columns = addAllColumnHeaders(CompanyTime);

            for (var i = 0; i < CompanyTime.length; i++) {
                var row$ = $('<tr/>');
                if (CompanyTime[i].Company == "KaladiAdmin"){

                }
                else {

                    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
                        var cellValue = CompanyTime[i][columns[colIndex]];

                        if (cellValue == null) { cellValue = ""; }

                        if (cellValue == true) {

                            row$.append($('<td><input type=\'checkbox\' name=\'Check\' checked=\'yes\'></input></td>'));
                        }
                        else if (cellValue == false) {
                            row$.append($('<td><input type=\'checkbox\' name=\'Check\' ></input></td>'));
                        }
                        else {
                            row$.append($('<td/>').html(cellValue));
                        }

                    }
                }
                if (CompanyTime[i].Company == "KaladiAdmin") {

                }
                else {
                    var button = "<button class=\"editButton\" style=\"background-color: #ffa500; color: #ffffff;\" >Update</button>" + 
                        "&nbsp;&nbsp;&nbsp;" +
                        "<button id=\"brnDelete\" class=\"btn btn-default btn-sm\" style=\"background-color: #ffa500; color: #ffffff;\">Remove</button>";
                    //var button = "<button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;</button>";
                    row$.append($('<td/>').html(button));
                }

                $("#excelDataTable").append(row$);
            }
        }

Button Event:

    $('button.editButton').click(function () {
        //var id = $(this).parent().siblings('.CID').text();

        console.log("clicked");
        //console.log(id);

    })

Thanks in advance!

Rolthar
  • 151
  • 2
  • 23

2 Answers2

1

Use event delegation to attach events to current and future (dynamically generated) elements.

   $('body').on('click','button.editButton',function () {
        //var id = $(this).parent().siblings('.CID').text();
        console.log("clicked");
        //console.log(id);
    });
HaukurHaf
  • 13,522
  • 5
  • 44
  • 59
0

As you're adding elements dynamically you should use delegation:

$(document).on('click', 'button.editButton', function () {
  // code
});
Andy
  • 61,948
  • 13
  • 68
  • 95