mars328
mars328

Reputation: 573

how to add event listener to the element inside cell of ag grid (with js or jquery, not angular, not reactjs, not vue)

I splited up the event listener and cellrender functions, but jquery function doesn't run at the bottom when I click the button for that. How can I add event listener to those two buttons.

//action column
let actionCellTemplate = (params) => {
    let device_id = params.data.id;
    let eDiv = document.createElement('div');
    eDiv.innerHTML = '<button type="button" class="btn btn-primary btn-alloc-token">Alloc Token</button>'+
                     '<button type="button" class="btn btn-success btn-client-secret">Client Key</button>';
    return eDiv;
}

// specify the columns
   let columnDefs = [
         { headerName: "ID", field: "id",  filter: 'agNumberColumnFilter', headerCheckboxSelection: true, headerCheckboxSelectionFilteredOnly: true, checkboxSelection: true },
         { headerName: "Name", field: "name", filter: "agTextColumnFilter", sortable: true },
         { headerName: "Location", field: "location", filter: "agTextColumnFilter", sortable: true },
         { headerName: "Active Tokens", field: "active_tokens", filter: "agTextColumnFilter", sortable: true },
         { headerName: "Action", field: "name", filter: "agTextColumnFilter", sortable: true, cellRenderer: actionCellTemplate },
   ];

$('.btn-alloc-token').on('click', function(){
   console.log("alloc");
})

Upvotes: 2

Views: 2634

Answers (1)

Antony Thompson
Antony Thompson

Reputation: 1638

You need to attach the event to something that exists when the page is loaded. Either a div around that button or usually I just use the body.

For example:

$('body').on('click', '.btn-alloc-token', function(){
   console.log("alloc");
})

This is called event bubbling or propogation. Here's a snippet from the jQuery documentation.

http://api.jquery.com/on/#direct-and-delegated-events

The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document element. In Internet Explorer 8 and lower, a few events such as change and submit do not natively bubble but jQuery patches these to bubble and create consistent cross-browser behavior.

Upvotes: 2

Related Questions