Arman
Arman

Reputation: 1442

Twitter Bootstrap Datatable not working properly with AJaX

Using this piece of HTML code is working fine as expected:

<table class = 'table table-bordered table-striped' id = 'example'>
    <thead><tr><th>Col1</th><th>Col2</th></tr></thead>
    <tbody>
        <tr><td>foo</td><td>foo</td></tr>
        <tr><td>foo</td><td>foo</td></tr>
    </tbody>
</table>

Here is it:

Correct view of Twitter Bootstrap Datatable

But when I store the same snippet in a variable as:

content = "<table class = 'table table-bordered table-striped' id = 'example'>" +
    "<thead><tr><th>Col1</th><th>Col2</th></tr></thead>" +
    "<tbody>" +
        "<tr><td>foo</td><td>foo</td></tr>" +
        "<tr><td>foo</td><td>foo</td></tr>" +
    "</tbody>" +
"</table>"

and call it dynamically via AJaX, the output seems to be different as shown in this screenshot:

enter image description here

The pagination and the search field are gone! There is no difference in the code, but why is the second table lacking those features?

Upvotes: 1

Views: 3599

Answers (1)

Bass Jobsen
Bass Jobsen

Reputation: 49044

After you add a table dynamically. You have to apply the dataTable() again. See this example: http://jsfiddle.net/bassjobsen/8GNpf/

Or for example add a table when the button with id="addtable" has been clicked:

var content = "<table class = 'table table-bordered table-striped' id = 'example2'>" +
    "<thead><tr><th>Col1</th><th>Col2</th></tr></thead>" +
    "<tbody>" +
        "<tr><td>foo</td><td>foo</td></tr>" +
        "<tr><td>foo</td><td>foo</td></tr>" +
    "</tbody>" +
"</table>"


$('#addtable').click(function(){$('body').append(content);

$('body table').last().dataTable({
        "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>"
    });});

Upvotes: 2

Related Questions