Reputation: 484
I am using datatables and fetching the data from an ajax URL. Each row of my returned table data includes a field that renders a button that looks like this:
<button type="button" data-catid="8" data-catname="Programming:JavaScript"></button>
The values assigned data-catid and data-catname come from the datatables retrieved data.
In certain cases, when the table finishes loading, I want to trigger a click on one of these buttons. My code for that is this:
$('#mydatatable').find('button[data-catid="9"]').trigger('click');
However, I cannot find a way to do this so that it occurs after the table has rendered and the button exists in the dom so I can find it and trigger the click.
I have tried drawCallback and initComplete but neither of those is triggered after the button has actually been added to the dom, allowing me to find it with jquery.
Is there a way I can do this? i.e. trigger my click after the mytable has finished retrieving its data via ajax and rendered it?
I am using datatables v 1.10
EDIT: Here is how my click event handler is attached to the summary table.
var selectedCat = 0;
$('#mydatatable :button').click(function () {
selectedCat = this.getAttribute("data-catId");
console.log("selecteCat is " + selectedCat);
qDetailTable.ajax.url('/datatables/question-data/' + selectedCat).load();
var selectedCatName = this.getAttribute("data-catName");
$('#questDetailCat').text('Questions about: ' + selectedCatName);
$('#questSummary').hide();
$('#questDetail').show();
});
Upvotes: 2
Views: 16863
Reputation: 58880
Move the click handler into a separate function, for example:
var selectedCat = 0;
function OnCategoryClick(btn){
selectedCat = btn.getAttribute("data-catId");
console.log("selecteCat is " + selectedCat);
qDetailTable.ajax.url('/datatables/question-data/' + selectedCat).load();
var selectedCatName = btn.getAttribute("data-catName");
$('#questDetailCat').text('Questions about: ' + selectedCatName);
$('#questSummary').hide();
$('#questDetail').show();
});
Event handler needs to be in a named function because you will not be able to trigger click event for elements that are not in DOM as with jQuery DataTables.
Change how you attach your click handler.
$('#mydatatable').on('click', 'button', function () {
OnCategoryClick(this);
});
Remember to always use delegated event handlers with elements inside jQuery DataTables because elements for pages other than first will not be available in DOM. See jQuery DataTables – Why click event handler does not work for more details.
Use $()
API method to locate required button and call your handler function OnCategoryClick()
.
var btn = $('#datatable-summary').DataTable().$('button[data-catid="9"]').get(0);
OnCategoryClick(btn);
Replace datatable-summary
with your actual ID of the summary table.
If you need to update details as soon as the summary table is initialized and drawn, use initComplete
option to define a callback and do it there.
Upvotes: 2