s

jquery data grid paging edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 12 December 2022 | 1092

This code snippet offers a comprehensive and adaptable solution for implementing pagination in web applications, particularly useful for developers working with ASP.NET MVC or other languages that involve front-end development. By leveraging jQuery for DOM manipulation and event handling, the script efficiently manages the display of large datasets in a paginated format. The core of the functionality lies in the paging JavaScript object, which encapsulates all the essential features of pagination, including initializing the pagination with given data, calculating the total number of pages, and handling navigation through different pages (first, last, next, previous). This modular approach not only simplifies the integration of the pagination system into various web projects but also ensures a high level of customization to cater to specific application needs.

The HTML structure, complemented by Bootstrap for styling, presents a user-friendly interface consisting of a dynamically generated list of items and a navigation bar for page control. The flexibility of the script is further demonstrated through the inclusion of a page size dropdown, allowing users to select the number of items displayed per page. This feature enhances the user experience by providing control over the data presentation. The script's design takes into account practical web development scenarios, offering a seamless way to integrate with backend data fetching processes. Whether used in a blog, e-commerce site, or a data-driven application, this pagination script is a valuable tool for developers seeking to present large sets of data in an organized, navigable, and aesthetically pleasing manner.

var paging = {
    init: function (data, currentPage, pageSize, pageNumberContainer, pageNumberTemplate, paginationCallbackFn) {
        this.data = data;
        this.pageSize = pageSize;
        this.pageNumberContainer = $("#" + pageNumberContainer);
        this.pageNumberTemplate = $("#" + pageNumberTemplate).html();
        this.currentPage = currentPage || 1;
        this.maxPagingNumber = 5;
        this.paginationCallback = paginationCallbackFn;
        this.pageCount = this.calculatePageCount();
    },
    calculatePageCount: function () {
        let pageCount = this.data.length / this.pageSize;
        return pageCount % 1 > 0 ? Math.trunc(pageCount) + 1 : Math.trunc(pageCount);
    },
    changePage: function (newPage) {
        this.currentPage = newPage;
        this.displaypaging();
        this.paginationClickFn();
    },
    first: function () {
        this.changePage(1);
    },
    last: function () {
        this.changePage(this.pageCount);
    },
    next: function () {
        if (this.currentPage < this.pageCount) {
            this.changePage(this.currentPage + 1);
        }
    },
    previous: function () {
        if (this.currentPage > 1) {
            this.changePage(this.currentPage - 1);
        }
    },
    displaypaging: function () {
        let startPage = this.currentPage - Math.trunc(this.maxPagingNumber / 2);
        startPage = Math.max(startPage, 1);
        let endPage = this.currentPage + Math.trunc(this.maxPagingNumber / 2);
        endPage = Math.min(endPage, this.pageCount);

        this.pageNumberContainer.empty();
        this.addPaginationButton("<<", () => this.first());
        this.addPaginationButton("<", () => this.previous());

        for (let index = startPage; index <= endPage; index++) {
            this.addPaginationButton(index, () => this.changePage(index));
        }

        this.addPaginationButton(">", () => this.next());
        this.addPaginationButton(">>", () => this.last());
    },
    addPaginationButton: function (label, action) {
        const btn = $(this.pageNumberTemplate).clone();
        const btnWithLabel = $(btn.html().replace('{{text}}', label));
        btnWithLabel.click(action);
        this.pageNumberContainer.append(btnWithLabel);
    },
    paginationClickFn: function () {
        const startIndex = (this.currentPage - 1) * this.pageSize;
        this.paginationCallback(this.currentPage, this.pageSize, startIndex);
    },
    show: function () {
        this.displaypaging();
        const startIndex = (this.currentPage - 1) * this.pageSize;
        this.paginationCallback(this.currentPage, this.pageSize, startIndex);
    }
};

HTML Code

<head>
    <style>
        #newsitems span {
            padding: 5px;
        }

        /* #paginationControls span {
            padding: 5px;
        }

        #paginationControls {
            margin-top: 20px;
        } */
    </style>
</head>

<body>
    <div id="content">
        <div id="news">
            <div id="newsitems">
            </div>

            <div class="container mt-4">
                <div class="d-flex justify-content-between align-items-center">

                    <!-- Pagination Links (on the left) -->
                    <nav>
                        <ul class="pagination mb-0" id="paginationControls">
                        </ul>
                    </nav>

                    <!-- Spacer for centering the dropdown -->
                    <div class="flex-grow-1 d-flex justify-content-center align-items-center">
                        <!-- Text "Page Size:" (in the center before dropdown) -->
                        <span class="mr-2">Page Size:</span>

                        <!-- Page Size Dropdown (in the center) -->
                        <select class="form-control w-auto" id="pageSize">
                            <option>5</option>
                            <option>10</option>
                            <option>20</option>
                            <option>50</option>
                            <option>100</option>
                            <option>250</option>
                            <option>500</option>
                            <option>1000</option>
                        </select>
                    </div>

                    <!-- Empty space on the right for symmetry -->
                    <div style="width: fit-content;"></div>
                </div>
            </div>

        </div>
    </div>
    <div id="pagenumbertemplate" style="display: none;">
        <li class="page-item"><span class="page-link">{{text}}</span></li>
    </div>
    <div id="contenttemplate">
        <div><span name="id"></span><span name="name"></span></div>
    </div>    
	   <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">

    <script type="text/javascript">
        var data = [{ id: 1, name: "Murugan" }, { id: 2, name: "Anantu" }, { id: 3, name: "Joyal" }, { id: 3, name: "Manjunath" }, { id: 5, name: "Mallikarjun" }, { id: 6, name: "Dnyaneshwar" }, { id: 7, name: "Deepika" }, { id: 8, name: "Raghavendra" }, { id: 9, name: "Salu" }, { id: 10, name: "Sanketh" }, { id: 11, name: "Sanketh" }, { id: 12, name: "Sanketh" }, { id: 13, name: "Sanketh" }, { id: 15, name: "Sanketh" }, { id: 15, name: "Sanketh" }, { id: 16, name: "Sanketh" },{ id: 1, name: "Murugan" }, { id: 2, name: "Anantu" }, { id: 3, name: "Joyal" }, { id: 3, name: "Manjunath" }, { id: 5, name: "Mallikarjun" }, { id: 6, name: "Dnyaneshwar" }, { id: 7, name: "Deepika" }, { id: 8, name: "Raghavendra" }, { id: 9, name: "Salu" }, { id: 10, name: "Sanketh" }, { id: 11, name: "Sanketh" }, { id: 12, name: "Sanketh" }, { id: 13, name: "Sanketh" }, { id: 15, name: "Sanketh" }, { id: 15, name: "Sanketh" }, { id: 16, name: "Sanketh" }];
    </script>
    <script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
    <script src="paging.js" type="text/javascript"></script>
    <script type="text/javascript">
		var defaultPageSize = parseInt($('#pageSize').val(), 10);
        paging.init(data, 1, defaultPageSize,'paginationControls','pagenumbertemplate', paginationclick);

        function paginationclick(currentPage, pageSize, dataIndex)
        {
            // write on click code here
			var container = $("#newsitems");
			container.empty();
			this.data.slice(dataIndex, dataIndex + pageSize).forEach( (ele) => {
				var content  = $($("#contenttemplate").html()).clone();
				$("[name='id']",content).html(ele.id);
				$("[name='name']",content).html(ele.name);
				container.append(content);
			});
            // write on click code here
        }
		$('#pageSize').change(function() {
			var selectedPageSize = parseInt($(this).val(), 10);
			paging.init(data, 1, selectedPageSize,'paginationControls','pagenumbertemplate', paginationclick);
			paging.show();
		});
		paging.show();
    </script>


</body>



    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>