How to correctly use of buttons inside HTML table cells

Viewed 301

In my HTML page I have a button in each row in a particular column. User may add new rows at runtime and these buttons are also inserted alongwith rest of the fields in each row.

The buttons are being appended using the following:

function funcAddBtnOpenPad() {   // This funct being called at page onload
// VARS FOR ADDING BUTTON IN CELL "5"
// STORING BUTTON ATTRIBUTES
var btnOpenPad = $('<input/>').attr({ type: 'button', id:'idBtnOpenPad', class:'clsBtnOpenPad', name:'btnOpenPad', value:'OpenPad' });

$('#childTable tr').each(function(tempRowIdx) {
    
// CONSTRUCT TAG FOR BUTTON "OpenPad" IN CELL "5"
    tempButtonCellTag = 'id_tIndx'+tempRowIdx+5;

// HERE WE ARE INSERTING THE BUTTON "OpenPad" <<<<
        $('#'+ tempButtonCellTag).append(btnOpenPad);
        $(this).find("input[type='button']").attr('id', 'idBtnOpenPad'+tempRowIdx);
});
}

However I find that only the first button is working when used in .on('click') function (as in the following):

$(function() {
    $('#idBtnOpenPad1').on('click', function() {
        alert("OpenPad clicked");
    });
});

I have tried to (manually) change the button to #idBtnOpenPad2 or #idBtnOpenPad3 etc, but it does not fire at all.

To get clarity, I am reproducing partial image of the table here:

enter image description here

Question is:

How to make use of buttons inside table cells correctly so that each of them function independently?

1 Answers

As suggested by @Swati, now instead of id, I am using class like this (method 1):

$(document).on('click', '.clsBtnOpenPad', function() {
    ...
});

Alternatively we may also use this (method 2):

$('#childTable').on('click', '.clsBtnOpenPad', function() {
    ...
});

Both work. Why was it not working earlier? Because I was trying to bind event to an element generated dynamically. Check for a detailed explanation here.

Also, using the second method is better as explained here.

Related