Richard
Richard

Reputation: 733

Access dynamically generated button

I am using jquery and datatables to generate edit and delete buttons dynamically. I need to access them later with javascript and I can't make it work.

I have this render function:

render: function (data) {
                            var actions = '';
                            actions += '<div class="btn-group btn-group-xs">';
                            actions += '<div id="'+data.id+'" class="buttonUpdate btn btn-primary"><span class="glyphicon glyphicon-pencil"></span></div>';
                            actions += '<div id="'+data.id+'" class="buttonDelete btn btn-danger"><span class="glyphicon glyphicon-trash"></span></div>';
                            actions += '</div>';
                            return actions;
                        }

And I can see the buttons showing correctly.

I try to get an event with:

    $('.buttonDelete').click( function () {
        alert('button clicked');
        console.log(this.id);
        //window.location.href = "{!! route('employee') !!}/"+employee_id;
    } );

But it is not doing anything :(.

How can i get the event and also how can I see if the button is generated correctly with the right id and class?

Upvotes: 1

Views: 611

Answers (1)

gaetanoM
gaetanoM

Reputation: 42044

Take a look at Delegated Events:

Change:

$('.buttonDelete').click( function () {

to:

$(document).on('click', '.buttonDelete', function () {

Upvotes: 7

Related Questions