ntalekt
ntalekt

Reputation: 852

Getting ID via JQuery for dynamic content

I'm creating some dynamic content tabs using PHP, one object on the tab is a datatable. I define the ID via PHP like this:

PHP:

echo '<table class="table table-striped table-bordered table-hover" id="'.$nospaces.'">';

The table loads the data perfectly however I'm having problems initializing the datatable for sorting and filtering. Normally on static tables I would just initialize it using the static ID but I can't do that in this case.

I thought I could do some jquery to listen to a tab click event and then grab the table ID and load it into the jquery datatables initialization but that isn't working either. I'm just getting an undefined alert:

JQuery:

<script>
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var row = $(this).closest('table').attr('id');
    alert(row);

    $(document).ready(function() {
    oTable = $('row').dataTable( {
       "sDom": '<"top"lf>rt<"bottom"ip><"clear">'

    });

    });
    });
</script>

Any help would be greatly appreciated! Thanks.

Upvotes: 0

Views: 108

Answers (3)

ntalekt
ntalekt

Reputation: 852

I ended up doing a mixture with some extra steps. Not the cleanest but it's working.

First on the dynamic tab/table I created a variable for a new ID because I had the tab and the table ID the same:

PHP:

$tableid = $nospaces .'table';
echo '<table class="table table-striped table-bordered table-hover" id="'.$tableid.'">';

I then initialize (and destroy) the datatable on tab click like this:

JQuery:

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
tab = e.target.hash // newly activated tab
tabtable = tab + 'table'

$(document).ready(function() {
    oTable = $(tabtable).dataTable( {
        "sDom": '<"top"lf>rt<"bottom"ip><"clear">'
    });
});
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    oldtab = e.relatedTarget.hash
    oldtable = oldtab + 'table'
    $(oldtable).dataTable().fnDestroy();
    });
});

Upvotes: 0

davidkonrad
davidkonrad

Reputation: 85558

I guess using the variable row would do the trick, instead of using the string 'row' :)

var row = $(this).closest('table').attr('id');
alert(row);

$(document).ready(function() {
oTable = $(row).dataTable( { //<--- here
  "sDom": '<"top"lf>rt<"bottom"ip><"clear">'
});

Upvotes: 1

Matt
Matt

Reputation: 1580

Is there any reason you can't still use the static ID?

var staticID = '<?php echo $nospaces; ?>';

$('#' + staticID).dataTable();

Upvotes: 1

Related Questions