iamjc015
iamjc015

Reputation: 2245

Identifying which button is clicked inside a table

so I have a DataTable and inside each row I put three buttons:

{
    "render": function(data, type, row, meta) {
        str = '<button id="edit" style="margin-right: 5px;margin-left:10px;" title="Edit" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-edit"></i></button>' +
            '<button id="view" style="margin-right: 5px;" title="View" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-eye"></i></button>' +
            '<button  title="Delete" class="btn btn-info deleteButton" data-value="' + row.spot_report_id + '"><i class="fa fa-trash"></i></button>';

        return str;
    }
}

I handle each click event like this:

$('#spot_reports_tbl').off('click').on('click', '.action', function(e) {
    var id = $(this).attr('data-value');
    console.log('Target: ' + e.target.id);
    switch (e.target.id) {
        case 'view':
            //view_spotreport(id);
            break;
        case 'edit':
            //edit_spot_report(id);
            break;
        default:
            alert('Cannot handle event. Contact IT Admini');
    }

});

The problem is, sometimes it gets the ID sucessfully and sometimes it did not get it. Why is that so?

Thanks!

Upvotes: 0

Views: 47

Answers (1)

Tushar
Tushar

Reputation: 87233

Use data-* attribute instead of id.

{
    "render": function(data, type, row, meta) {
        str = '<button data-action="edit" style="margin-right: 5px;margin-left:10px;" title="Edit" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-edit"></i></button>' +
            '<button data-action="view" style="margin-right: 5px;" title="View" class="btn btn-info action" data-value="' + row.spot_report_id + '"><i class="fa fa-eye"></i></button>' +
            '<button  title="Delete" class="btn btn-info deleteButton" data-value="' + row.spot_report_id + '"><i class="fa fa-trash"></i></button>';

        return str;
    }
}

Event handling:

$(document).on('click', '.action', function(e) {
    var action = $(this).data('action'); // Get action data attribute value

    switch (action) {
        case 'view':
            //view_spotreport(id);
            break;
        case 'edit':
            //edit_spot_report(id);
            break;
        default:
            alert('Cannot handle event. Contact IT Admini');
    }

});

Upvotes: 2

Related Questions