AlexP2014
AlexP2014

Reputation: 211

HTML Client side pagination - Cant get dynamically added data

So I'm using a javascript pagination http://en.newinstance.it/2006/09/27/client-side-html-table-pagination-with-javascript/ which works great.. except for when I try to load my dynamically added data (from a getJSON). The issue is that it is checking the table but not finding any results as it is injected into the innerHTML and not "hard-coded" in I guess.

this is the javascript

script(type='text/javascript')    
    pager = new Pager('results', 3);
      pager.init();
      pager.showPageNav('pager', 'pageNavPosition');
      pager.showPage(1);   

Does anyone know what I can do to fix this? I've tried using some of the proper datagrid but I cannot get them to work with my application.

$.getJSON( '/getlocations', function( data ) {
        userListData = data;

        // For each item in our JSON, add a table row and cells to the content string
        $.each(data, function(){
            tableContent += '<tr>';
            tableContent += '<td><a href="#" class="linkshowuser" rel="' + this.name + '" title="Show Details">' + this.name + '</a></td>';
            tableContent += '<td>' + this.information + '</td>';
            tableContent += '<td>' + this.lat + '</td>';
            tableContent += '<td>' + this.lon + '</td>';
            tableContent += '<td><button onclick="viewLocationOnMap()">View on map</button></td>';
            tableContent += '<td>In Progress</button></td>';
            tableContent += '<td><a href="#" class="linkdeleteitem" rel="' + this._id + '">delete</a></td>';
            tableContent += '</tr>';
        });

        // Inject the whole content string into our existing HTML table
        $('#userList table tbody').html(tableContent);

Thanks

Upvotes: 0

Views: 2834

Answers (1)

ivan.sim
ivan.sim

Reputation: 9288

Not exactly sure what your <table> HTML looks like, I notice that if I tried to initalize the pagination with an empty HTML table i.e. no rows, the browser console will throw an error:

Uncaught TypeError: Cannot set property 'className' of null

The paging.js seems to rely on the fact that the <tr> rows exist and are styled with certain CSS classes, namely, .pg-normal and .pg-selected defined. Anyway, I manage to get your codes to work by:

  1. Instantiating the pagination after the <tr> HTML are appended, and
  2. Replace $('#userList table tbody').html(tableContent); with $('#result').append(tableContent); since result is the ID of the table used in the initializing the pagination.

Take a look at the stack snippet below or this jsfiddle:

/*** Javascript ***/
// For each item in our JSON, add a table row and cells to the content string
var data = [
    {id:1, name:'cell1', information:'First Row'},
    {id:2, name:'cell2', information:'Second Row'},
    {id:3, name:'cell3', information:'Third Row'},
    {id:4, name:'cell4', information:'Fourth Row'},
    {id:5, name:'cell5', information:'Fifth Row'},
    {id:6, name:'cell6', information:'Sixth Row'},
    {id:7, name:'cell7', information:'Seventh Row'},
    {id:8, name:'cell8', information:'Eighth Row'},
    {id:9, name:'cell9', information:'Nineth Row'},
];
var tableContent = "";
$.each(data, function(){
    tableContent += '<tr>';
    tableContent += '<td><a href="#" class="linkshowuser" rel="' + this.name + '" title="Show Details">' + this.information + '</a></td>';
    tableContent += '<td><button onclick="viewLocationOnMap()">View on map</button></td>';
    tableContent += '<td>In Progress</button></td>';
    tableContent += '<td><a href="#" class="linkdeleteitem" rel="' + this._id + '">Delete</a></td>';
    tableContent += '</tr>';
});

// Inject the whole content string into our existing HTML table
$('#results').append(tableContent);

// Instantiate pagination after data is available    
pager = new Pager('results', 3);
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
      
// pagination object codes.
function Pager(tableName, itemsPerPage) {
    this.tableName = tableName;
    this.itemsPerPage = itemsPerPage;
    this.currentPage = 1;
    this.pages = 0;
    this.inited = false;

    this.showRecords = function (from, to) {
        var rows = document.getElementById(tableName).rows;
        // i starts from 1 to skip table header row
        for (var i = 1; i < rows.length; i++) {
            if (i < from || i > to) rows[i].style.display = 'none';
            else rows[i].style.display = '';
        }
    }

    this.showPage = function (pageNumber) {
        if (!this.inited) {
            alert("not inited");
            return;
        }

        var oldPageAnchor = document.getElementById('pg' + this.currentPage);
        oldPageAnchor.className = 'pg-normal';

        this.currentPage = pageNumber;
        var newPageAnchor = document.getElementById('pg' + this.currentPage);
        newPageAnchor.className = 'pg-selected';

        var from = (pageNumber - 1) * itemsPerPage + 1;
        var to = from + itemsPerPage - 1;
        this.showRecords(from, to);
    }

    this.prev = function () {
        if (this.currentPage > 1) this.showPage(this.currentPage - 1);
    }

    this.next = function () {
        if (this.currentPage < this.pages) {
            this.showPage(this.currentPage + 1);
        }
    }

    this.init = function () {
        var rows = document.getElementById(tableName).rows;
        var records = (rows.length - 1);
        this.pages = Math.ceil(records / itemsPerPage);
        this.inited = true;
    }

    this.showPageNav = function (pagerName, positionId) {
        if (!this.inited) {
            alert("not inited");
            return;
        }
        var element = document.getElementById(positionId);
        var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> &#171 Prev </span> | ';
        for (var page = 1; page <= this.pages; page++)
            pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> | ';
        pagerHtml += '<span onclick="' + pagerName + '.next();" class="pg-normal"> Next &#187;</span>';
        element.innerHTML = pagerHtml;
    }
}
/*** CSS ***/
table {
    border: 1px solid lightgray;    
}

th, td{
    border:1px solid lightgray;
    padding:5px;
}

.pg-normal {
    color: black;
    font-weight: normal;
    text-decoration: none;    
    cursor: pointer;    
}

.pg-selected {
    color: black;
    font-weight: bold;        
    text-decoration: underline;
    cursor: pointer;
}
<!--- HTML --->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="results">
    <tr>
        <th>ID</th>
        <th>Information</th>
        <th>Status</th>
        <th>Actions</th>
    </tr>     
</table>
<div id="pageNavPosition"></div>

Upvotes: 2

Related Questions