</link> <link rel="stylesheet" href="https://tutorialshelper.com/demo/Css/dynamictable.css"> <title>Page" /></link> <link rel="stylesheet" href="https://tutorialshelper.com/demo/Css/dynamictable.css"> <title>Page" />
Dynamic table from JSON schema with filters using javascript

Updated : Dec 14, 2019 in Articles

Dynamic table from JSON object with filters using javascript

in this article, we will learn about how to implement HTML Dynamic table from JSON object with filters using javascript step by step

Go to visual code add HTML page follow the given below HTML page

dynamictable.html

<!DOCTYPE html>
<html>
<head>
        <link rel="stylesheet" href="../DynamicTable/pagenation.css"></link>
        <link rel="stylesheet" href="https://tutorialshelper.com/demo/Css/dynamictable.css">
  
<title>Page Title</title>
</head>
<body>      
        <div class="panel">
                <div class="body">
                    <div class="input-group">
                        <label for="searchBox">Filter</label>
                        <input type="search" id="searchBox" placeholder="Filter...">
                    </div>
                </div>
            </div>
            <br>
    <div class="tables" id="showData"></div>
</body>
</html>
<script src="../DynamicTable/test.js"></script>
<script src="../DynamicTable/Pagenation.js"></script>

  

before implementing the javascript functionality for a dynamical table we need restful API in this example we will user test APIs

follow the given below some of test Apis

https://jsonplaceholder.typicode.com/photos
http://dummy.restapiexample.com/api/v1/employees
https://jsonplaceholder.typicode.com/todos/

Dynamictable.js

var request = new XMLHttpRequest()
request.open('GET', 'https://jsonplaceholder.typicode.com/photos', true)
request.onload = function() {
  // Begin accessing JSON data here
  var jsondata = JSON.parse(this.response)
            //get the table headers 
            var col = [];
            window.cols = col;
            for (var i = 0; i < jsondata.length; i++) {
                for (var key in jsondata[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
                break;
            }
            var pkid = col[0];
            //table pk id for editing or deleting table 
            window.pkid = pkid;
            col.push("Actons");
            var thead = document.createElement("thead");
            var table = document.createElement("table");
            table.setAttribute('class', 'table blueTable Datagrid');
            table.setAttribute('id', 'Datagrid');
         

            var tr =table.insertRow(-1);
            for (var i = 0; i < col.length; i++) {
                var th = document.createElement("th");
                th.innerHTML = col[i];
                tr.appendChild(th);
            }
            //thead.append(tr);
            for (var i = 0; i < jsondata.length; i++) {
                tr = table.insertRow(-1);
                for (var j = 0; j < col.length; j++) {
                    var tabCell = tr.insertCell(-1);
                    var checkdata = jsondata[i][col[j]];
                        tabCell.innerHTML = jsondata[i][col[j]];
                }
                var g = window.pkid;
                var PktableId = jsondata[i][g];
                tabCell.innerHTML = '<a href="#" onclick="return EditTable(' + PktableId + ')">Edit</a> | <a href="#" onclick="DeleteTable(' + PktableId + ')">Delete</a></td>'
            }
            var divContainer = document.getElementById("showData");
            divContainer.innerHTML = "";
            divContainer.appendChild(table);
            pagenation();
          
}  
request.send()
function pagenation()
{
    let options = {
        numberPerPage:20, 
        goBar:true, 
        pageCounter:true, 
    };
    let filterOptions = {
        el:'#searchBox' 
    };
    paginate.init('#Datagrid',options,filterOptions);
}

the given below javascript function is helpful for pagination

the given below pagination function you will call at dynamictable .js file and set how many rows you want to display in a table

pagenation.js

(function(window){
    'use strict';
    function lignePaginate(){
        var _lignePaginate = {};
        _lignePaginate.init = function(el, options = {numberPerPage: 10,goBar:false,pageCounter:true},filter = [{el: null}]
        ){
            setTableEl(el);
            initTable(_lignePaginate.getEl());
            checkIsTableNull();
            setOptions(options);
            setConstNumberPerPage(options.numberPerPage);
            setFilterOptions(filter);
            launchPaginate();
        }
        /**
         * Configuraciones de la paginacion
         **/
        var settings = {
            el:null,
            table:null,
            numberPerPage:10,
            constNumberPerPage:10,
            numberOfPages:0,
            goBar:false,
            pageCounter:true,
            hasPagination:true,
        };

        var filterSettings = {
            el:null,
            filterBox:null,
            trs:null,
        }

        /**
         * Setters private
         **/

        var setConstNumberPerPage = function(number){
            settings.constNumberPerPage = number;
        }
        var setNumberPerPage = function(number){
            settings.numberPerPage = number;
        }

        var initTable = function(el){
            if(el.indexOf('#') > -1 ){
                settings.table = document.getElementById(el.replace('#','').trim());
            }else if(el.indexOf('.') > -1  ){
                settings.table = document.querySelector(el);
            }
        }

        var iniFilter = function(el){
            if(el.indexOf('#') > -1 ){
                filterSettings.filterBox = document.getElementById(el.replace('#','').trim());
            }else if(el.indexOf('.') > -1  ){
                filterSettings.filterBox = document.querySelector(el);
            }
        }

        var setTableEl = function(el){
            settings.el = el;
        }

        var setFilterOptions = function (filterOptions) {
            if(filterOptions.el != null){
                setFilterEl(filterOptions.el);
                iniFilter(filterSettings.el);
                checkIsFilterBoxNull();
                setFunctionInFilterBox();
            }
        }

        var setFilterEl = function(el){
            filterSettings.el = el;
        }

        var setFunctionInFilterBox = function(){
            filterSettings.filterBox.setAttribute('onkeyup','paginate.filter()')
        }

        var setGoBar = function(value){
            settings.goBar = value;
        }

        var setPageCounter = function(value){
            settings.pageCounter = value;
        }

        /**
         * Getters public
         **/


        _lignePaginate.getEl = function(){
            return settings.el;
        }
        _lignePaginate.getTable = function(){
            return settings.table;
        }
        _lignePaginate.getNumberPerPage = function(){
            return settings.numberPerPage;
        }

        _lignePaginate.getConstNumberPerPage = function(){
            return settings.constNumberPerPage;
        }

        /**
         * Private Methods
         **/

        var table,tr = [],pageCount,numberPerPage,th;

        var setOptions = function(options){
            if(options.numberPerPage != settings.numberPerPage){
                setNumberPerPage(options.numberPerPage);
            }

            if(typeof options.goBar === 'boolean')
                setGoBar(options.goBar);

            if(typeof options.pageCounter === 'boolean')
                setPageCounter(options.pageCounter);
        }

        var checkIsTableNull = function(){
            if(settings.table == null){
                throw new Error('Element ' + _lignePaginate.getEl() + ' no exits');
            }
        }

        var checkIsFilterBoxNull = function(){
            if(filterSettings.filterBox == null){
                throw new Error('Element ' + _lignePaginate.getEl() + ' no exits');
            }
        }

        var paginateAlreadyExists = function() {
            let paginate = document.querySelector('div.paginate');
            if(paginate != null)
                removePaginate(paginate);
        }

        var removePaginate = function(element){
            element.parentNode.removeChild(element);
        }

        var hiddenPaginateControls = function(){
            document.querySelector('.paginate_controls').style.visibility = 'hidden';
        }

        var showPaginatecontrols = function(){
            document.querySelector('.paginate_controls').style.visibility = 'unset';
        }
       
        var pageButtons = function(numberOfPage,currentPage) {
          
            let	prevDisabled = (currentPage == 1)?"disabled":"";
            let nextDisabled = (currentPage == numberOfPage)?"disabled":"";

           
            let buttons = "<input type='button' value='prev' class='paginate_control_prev' onclick='paginate.sort("+(currentPage - 1)+")' "+prevDisabled+">";
            let buttonNumberOfPage = "<input type='button' value='" + currentPage + ' - ' + numberOfPage + "' disabled>";

            for (let $i=1; $i<=numberOfPage;$i++){
                if(numberOfPage > 10){
                    buttons += paginationMoreThatTenPage($i,numberOfPage);
                }else{
                    buttons += "<input type='button' id='id"+$i+"'value='"+$i+"' onclick='paginate.sort("+$i+")'>";
                }
            }

            let nextButton = "<input type='button' value='next' class='paginate_control_next' onclick='paginate.sort("+(currentPage + 1)+")' "+nextDisabled+">";
            buttons +=  nextButton;

            if(settings.pageCounter)
                buttons += buttonNumberOfPage;

            if(settings.goBar)
                buttons += addGoToPage();

            return buttons;
        }
        
        var paginationMoreThatTenPage = function(iterator,numberOfPage){

            let referenceForTheLast = numberOfPage - 1;
            let middleValue = '...';

            if(iterator > referenceForTheLast || iterator < 5){
                return "<input type='button' id='id"+iterator+"'value='"+iterator+"' onclick='paginate.sort("+iterator+")'>";
            }else if((iterator + 1) == numberOfPage) {
                return middleValue + "<input type='button' id='id"+iterator+"'value='"+iterator+"' style='display: none' onclick='paginate.sort("+iterator+")'>";
            }else {
                return "<input type='button' id='id"+iterator+"'value='"+iterator+"' style='display: none' onclick='paginate.sort("+iterator+")'>";
            }
        }

        var addGoToPage = function(){
            let inputBox = "<input type='number' id='paginate_page_to_go' value='1' min='1' max='"+ settings.numberOfPages +"'>";
            let goButton = "<input type='button' id='paginate-go-button' value='Go' onclick='paginate.goToPage()'>  ";
            return inputBox + goButton;
        }

        _lignePaginate.goToPage = function(){
            let page = document.getElementById("paginate_page_to_go").value;
            _lignePaginate.sort(page);
        }

        var launchPaginate = function(){
            paginateAlreadyExists();
            table = settings.table;
            numberPerPage = settings.numberPerPage;
            let rowCount = table.rows.length;
           
            let firstRow = table.rows[0].firstElementChild.tagName;
          
            let hasHead = (firstRow === "TH");
          
            let $i,$ii,$j = (hasHead)?1:0;
          
            th = (hasHead?table.rows[(0)].outerHTML:"");
            pageCount = Math.ceil(rowCount / numberPerPage);
            settings.numberOfPages = pageCount;

            if (pageCount > 1) {
                settings.hasPagination = true;
                for ($i = $j,$ii = 0; $i < rowCount; $i++, $ii++)
                    tr[$ii] = table.rows[$i].outerHTML;
                
                table.insertAdjacentHTML("afterend","<div id='buttons' class='paginate paginate_controls'></div");
                
                _lignePaginate.sort(1);
            }else{
                settings.hasPagination = false;
            }
        };

        _lignePaginate.sort = function(selectedPageNumber) {
            
            let rows = th,startPoint = ((settings.numberPerPage * selectedPageNumber)-settings.numberPerPage);
            for (let $i = startPoint; $i < (startPoint+settings.numberPerPage) &amp;&amp; $i < tr.length; $i++)
                rows += tr[$i];

            table.innerHTML = rows;
            document.getElementById("buttons").innerHTML = pageButtons(pageCount,selectedPageNumber);
            document.getElementById("id"+selectedPageNumber).classList.add('active');
           
            document.getElementById("id"+selectedPageNumber).style.display = 'unset';
        }

        
        _lignePaginate.filter = function() {
            if(settings.hasPagination){
                setNumberPerPage(9999);
                _lignePaginate.sort(1);
                hiddenPaginateControls();
            }
            const filter = document.querySelector(filterSettings.el).value.toUpperCase();
            const trs = document.querySelectorAll( settings.el + ' tr:not(.header)');
            trs.forEach(tr => tr.style.display = [...tr.children].find(td => td.innerHTML.toUpperCase().includes(filter)) ? '' : 'none');

            if(filter.length == 0 &amp;&amp; settings.hasPagination){
                setNumberPerPage(_lignePaginate.getConstNumberPerPage());
                _lignePaginate.sort(1);
                showPaginatecontrols();
            }

        }

        return _lignePaginate;
    }

    if(typeof(window.paginate) === 'undefined'){
        window.paginate = lignePaginate();
    }
})(window);

pagenation.css

div.paginate{
    padding: 5px 0px;
    margin: auto;
}
div.paginate input[type='button']:hover{
    cursor: pointer;
}
div.paginate input[type='button']{
    margin: 0px 2px;
    border: none;
    color: #03A9F4;
    background-color: transparent;
    border-radius: 50%;
    min-width: 1.5rem;
    min-height: 1.5rem;
    outline: none;
}

div.paginate input[type='button'].active{
    background-color: #17a2b8;
    color: #fff;
    font-weight: bold;
}
div.paginate input[type='button']:disabled{
    color: grey!important;
    cursor: not-allowed;
}

div.paginate input[type='number']#paginate_page_to_go{
    max-width: 3rem;
    text-align: center;
    border-radius: 4px;
    border: 1px solid rgba(128, 128, 128, 0.65);
    padding: 3px;
}
.Datagrid th {
    background: #1C6EA4;
    background: -moz-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
    background: -webkit-linear-gradient(top, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
    background: linear-gradient(to bottom, #5592bb 0%, #327cad 66%, #1C6EA4 100%);
    border-bottom: 2px solid #444444;
    color: white;
    padding: 8px 1px;
    text-align: center;
    text-transform: uppercase;
}

try to run your application

try to run this example by using different APIs

request.open(‘GET’, ‘https://jsonplaceholder.typicode.com/photos’, true)

View Demo

Dynamic table from JSON schema with filters using javascript

Latest posts by DuttaluruVijayakumar (see all)
Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x