How to convert HTML table into jQuery DataTable?

datatables, html, javascript, jquery

Solution

In order for DataTables to be able to function correctly, the HTML for the target table must be laid out in a well formed manner with the 'thead' and 'tbody' sections declared. For example:

<table id="table_id">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>etc</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row 1 Data 1</td>
            <td>Row 1 Data 2</td>
            <td>etc</td>
        </tr>
        <tr>
            <td>Row 2 Data 1</td>
            <td>Row 2 Data 2</td>
            <td>etc</td>
        </tr>
    </tbody>
</table>

Problem

I've tried this: ``` <html> <body> <script type="text/JavaScript" src="/DataTables/jquery-1.4.2.js"></script> <script type="text/JavaScript" src="/DataTables/jquery.dataTables.js"></script> <table id="myTableId"> <tr> <td>Enter Rows</td> <td><input type="number" id="txtRows"/></td> </tr> <tr> <td>Enter Columns</td> <td><input type="number" id="txtCols"/></td> </tr> <tr> <td colspan="2"><input type="button" id="btnDisplay" value="Display" onClick="ShowTable();"/></td> </tr> </table> <table id="tbl_DynamicTable" border="1" style="display:none"> </table> </body> <script type="text/JavaScript"> function ShowTable() { document.getElementById("tbl_DynamicTable").style.display = ""; createTable(); } function createTable() { var rows = document.getElementById("txtRows").value; var cols = document.getElementById("txtCols").value; var table = document.getElementById("tbl_DynamicTable"); var str=""; var randomColor; for(var i=0;i<rows;i++) { randomColor = '#'+Math.floor(Math.random()*16777215).toString(16); str += "<tr id=row" + i +" bgcolor="+randomColor+">"; for(var j=0;j<cols;j++) { if(i==0) { str += "<th> Header " + j + "</th>"; } else { str += "<td> Row " + i + ", Cell "+ j + "</td>"; } } str += "</tr>"; } table.innerHTML = str; $("#myTableId").dataTable(); } </script> </html> ``` I want to convert this table into jQuery DataTable. It's showing error `Uncaught ReferenceError: $ is not defined [repeated 2 times]`. How to solve this? I want to use this jQuery DataTable to Searching and paging function. But first want to convert it into DataTable first.

Original source