Search code examples
javascriptdatatablesxpages

initiate datatables on xp:table control


On an XPage I have a table component:

<xp:table id="tblProposals">

on which I want to initiate the datatables plugin on via a scriptblock component:

<xp:scriptBlock id="scriptInitProposals">
                                <xp:this.value><![CDATA[$(document).ready(function() {

    var tableId = x$("#{id:tblProposals}");
    $("#" + tableId.get(0).id).DataTable();
initProposals("#" + tableId.get(0).id,"getProposals");
    $('table th:first').removeClass('sorting_asc');
});]]></xp:this.value>
                            </xp:scriptBlock>

my JS function starts as followed:

function initProposals(id, method) {
alert(id)
var db = $(id).DataTable();
db.destroy();
localStorage.clear();

var table = $(id).DataTable({

    "pageLength": pageLength,
    "ajax": "api.xsp/reports?method=" + method,...

when I choose a normal html table with id (e.g. and run scriptblock:

<xp:scriptBlock id="scriptInitProposals">
                                <xp:this.value><![CDATA[$(document).ready(function() {
    $('#tblProposals').DataTable();
    initProposals("#tblProposals","proposals");
    $('table th:first').removeClass('sorting_asc');
});]]></xp:this.value>
                            </xp:scriptBlock>

The table is generated just fine.

It seems the datatables plugin is not so happy with the dynamic id or am I missing something??


Solution

  • What you get with x$("#{id:tblProposals}") is not the id but the DOM jQuery wrapped DOM object already, if I'm not mistaken.

    Then, you repeat the DataTable() call twice: before calling initProposals and inside it. I think you can remove one.

    At this point you might want to change what you pass to initProposals, either the id or the object, or any of them and then handle it in the method. You could do something like this:

    <xp:scriptBlock value="$(document).ready(function() {
            initProposals('#{id:tblProposals}', 'getProposals');
            $('table th:first').removeClass('sorting_asc');
        });"/>
    

    Then you slightly modify your function:

    function initProposals(id, method) {
        var element = $(document.getElementById(id));
        var table = element.DataTable();
        table.destroy();
        localStorage.clear();
    
        element.DataTable({