skip to Main Content

I’m encountering an issue with my search box. When I clear it, all the data in my pagination appears. My objective is for it to return only the five data entries displayed on the currently active page when cleared.

document.getElementById("myInput").addEventListener("input", searchTable);

function searchTable() {
  var input, filter, table, tr, td, i, j, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 1; i < tr.length; i++) {
    var displayRow = false;
    td = tr[i].getElementsByTagName("td");
    for (j = 0; j < td.length; j++) {
      if (td[j]) {
        txtValue = td[j].textContent || td[j].innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
          displayRow = true;
          break; // Break the inner loop if match found in any column
        }
      }
    }
    if (displayRow) {
      tr[i].style.display = "";
      displayPagination();
    } else {
      tr[i].style.display = "none";
    }
  }
}

document.addEventListener("DOMContentLoaded", function() {
  const table = document.getElementById("myTable");
  const tbody = table.querySelector("tbody");
  const dataRows = Array.from(tbody.getElementsByTagName("tr")).slice(1); // Exclude header row
  const headerRow = table.querySelector(".header");
  const itemsPerPage = 5;
  let currentPage = 1;

  function displayRows(page) {
    const startIndex = (page - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    dataRows.forEach((row, index) => {
      if (index >= startIndex && index < endIndex) {
        row.style.display = "";
      } else {
        row.style.display = "none";
      }
    });
  }

  function displayPagination() {
    const pageCount = Math.ceil(dataRows.length / itemsPerPage);
    const paginationDiv = document.querySelector(".pagination");
    paginationDiv.innerHTML = "";

    // Previous button
    const prevButton = document.createElement("button");
    prevButton.textContent = "Prev";
    prevButton.addEventListener("click", function() {
      if (currentPage > 1) {
        currentPage--;
        displayRows(currentPage);
        updatePaginationButtons();
      }
    });
    paginationDiv.appendChild(prevButton);

    // Page buttons
    for (let i = 1; i <= pageCount; i++) {
      const button = document.createElement("button");
      button.textContent = i;
      if (i === currentPage) {
        button.classList.add("active");
      }
      button.addEventListener("click", function() {
        currentPage = i;
        displayRows(currentPage);
        updatePaginationButtons();
      });
      paginationDiv.appendChild(button);
    }

    // Next button
    const nextButton = document.createElement("button");
    nextButton.textContent = "Next";
    nextButton.addEventListener("click", function() {
      if (currentPage < pageCount) {
        currentPage++;
        displayRows(currentPage);
        updatePaginationButtons();
      }
    });
    paginationDiv.appendChild(nextButton);
  }

  function updatePaginationButtons() {
    const paginationButtons = document.querySelectorAll(".pagination button");
    paginationButtons.forEach((button, index) => {
      if (index === currentPage) {
        button.classList.add("active");
      } else {
        button.classList.remove("active");
      }
    });
  }

  // Initially display header row
  headerRow.style.display = "";

  displayRows(currentPage);
  displayPagination();
});
<input type="text" id="myInput" placeholder="Search for names.." title="Type in a name" />
<table id="myTable">
  <tr class="header">
    <th>#</th>
    <th style="width: 60%">Name</th>
    <th style="width: 40%">Country</th>
    <th style="width: 40%">Age</th>
    <th style="width: 40%">Email</th>
    <th style="width: 40%">Surname</th>
    <th style="width: 40%">Middlename</th>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
    <td>31</td>
    <td>[email protected]</td>
    <td>Alfie</td>
    <td>Papa</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
    <td>21</td>
    <td>[email protected]</td>
    <td>shy</td>
    <td>Mama</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Island Trading</td>
    <td>UK</td>
    <td>31</td>
    <td>[email protected]</td>
    <td>xerxe</td>
    <td>cici</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Koniglich Essen</td>
    <td>Germany</td>
    <td>54</td>
    <td>[email protected]</td>
    <td>naknak</td>
    <td>fiif</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
    <td>43</td>
    <td>[email protected]</td>
    <td>neknek</td>
    <td>pekpek</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
    <td>23</td>
    <td>[email protected]</td>
    <td>hikhik</td>
    <td>hokhok</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>North/South</td>
    <td>UK</td>
    <td>32</td>
    <td>[email protected]</td>
    <td>tektek</td>
    <td>kita</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Paris specialites</td>
    <td>France</td>
    <td>65</td>
    <td>[email protected]</td>
    <td>tektek</td>
    <td>leklek</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Koniglich Essen</td>
    <td>Germany</td>
    <td>54</td>
    <td>[email protected]</td>
    <td>naknak</td>
    <td>fiif</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
    <td>43</td>
    <td>[email protected]</td>
    <td>neknek</td>
    <td>pekpek</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
    <td>23</td>
    <td>[email protected]</td>
    <td>hikhik</td>
    <td>hokhok</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>North/South</td>
    <td>UK</td>
    <td>32</td>
    <td>[email protected]</td>
    <td>tektek</td>
    <td>kita</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Paris specialites</td>
    <td>France</td>
    <td>65</td>
    <td>[email protected]</td>
    <td>tektek</td>
    <td>leklek</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Koniglich Essen</td>
    <td>Germany</td>
    <td>54</td>
    <td>[email protected]</td>
    <td>naknak</td>
    <td>fiif</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
    <td>43</td>
    <td>[email protected]</td>
    <td>neknek</td>
    <td>pekpek</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
    <td>23</td>
    <td>[email protected]</td>
    <td>hikhik</td>
    <td>hokhok</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>North/South</td>
    <td>UK</td>
    <td>32</td>
    <td>[email protected]</td>
    <td>tektek</td>
    <td>kita</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Paris specialites</td>
    <td>France</td>
    <td>65</td>
    <td>[email protected]</td>
    <td>tektek</td>
    <td>leklek</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Koniglich Essen</td>
    <td>Germany</td>
    <td>54</td>
    <td>[email protected]</td>
    <td>naknak</td>
    <td>fiif</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
    <td>43</td>
    <td>[email protected]</td>
    <td>neknek</td>
    <td>pekpek</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
    <td>23</td>
    <td>[email protected]</td>
    <td>hikhik</td>
    <td>hokhok</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>North/South</td>
    <td>UK</td>
    <td>32</td>
    <td>[email protected]</td>
    <td>tektek</td>
    <td>kita</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="name1" />&nbsp;</td>
    <td>Paris specialites</td>
    <td>France</td>
    <td>65</td>
    <td>[email protected]</td>
    <td>tektek</td>
    <td>leklek</td>
  </tr>
</table>

I attempted to resolve the issue by placing the displayPagination() function within the Sort function, but it’s still not functioning properly. Additionally, when I try to search again, all the data appears in my table.

2

Answers


  1. To make the table only display the rows that are on the 1st pagination page when the search box is cleared, There are some adjustments that need to be done in the searchTable function. like resetting all rows to hidden before searching, handling the empty search separately, and displayRow reset for each row to filter according to the search.

    Additionally, There are a lot of bad practices in the code you have provided from using var to the structure & formatting of the code. I have made some changes and added the maximum best practices in this updated version of the JS code you provided which hopefully also meets your requirements and fixes the issue you were facing.

    document.addEventListener("DOMContentLoaded", function () {
        const table = document.getElementById("myTable");
        const tbody = table.querySelector("tbody");
        const dataRows = Array.from(tbody.getElementsByTagName("tr")).slice(1); // Not Include header row
        const headerRow = table.querySelector(".header");
        const itemsPerPage = 5;
        let currentPage = 1;
    
        // Function to display rows according to the current page
        function displayRows(page) {
            const startIndex = (page - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;
            dataRows.forEach((row, index) => {
                if (index >= startIndex && index < endIndex) {
                    row.style.display = "";
                } else {
                    row.style.display = "none";
                }
            });
        }
    
        // Function to display pagination
        function displayPagination() {
            const pageCount = Math.ceil(dataRows.length / itemsPerPage);
            const paginationDiv = document.querySelector(".pagination");
            paginationDiv.innerHTML = "";
    
            // Previous button
            const prevButton = document.createElement("button");
            prevButton.textContent = "Prev";
            prevButton.addEventListener("click", function () {
                if (currentPage > 1) {
                    currentPage--;
                    displayRows(currentPage);
                    updatePaginationButtons();
                }
            });
            paginationDiv.appendChild(prevButton);
    
            // Page buttons
            for (let i = 1; i <= pageCount; i++) {
                const button = document.createElement("button");
                button.textContent = i;
                if (i === currentPage) {
                    button.classList.add("active");
                }
                button.addEventListener("click", function () {
                    currentPage = i;
                    displayRows(currentPage);
                    updatePaginationButtons();
                });
                paginationDiv.appendChild(button);
            }
    
            // Next button
            const nextButton = document.createElement("button");
            nextButton.textContent = "Next";
            nextButton.addEventListener("click", function () {
                if (currentPage < pageCount) {
                    currentPage++;
                    displayRows(currentPage);
                    updatePaginationButtons();
                }
            });
            paginationDiv.appendChild(nextButton);
        }
    
        // Function to update pagination buttons
        function updatePaginationButtons() {
            const paginationButtons = document.querySelectorAll(".pagination button");
            paginationButtons.forEach((button, index) => {
                if (index === currentPage) {
                    button.classList.add("active");
                } else {
                    button.classList.remove("active");
                }
            });
        }
    
        // Function to search the table
        function searchTable() {
            const input = document.getElementById("myInput");
            const filter = input.value.toUpperCase();
            let displayRow = false;
    
            // Reset all rows to be hidden
            dataRows.forEach(row => row.style.display = "none");
    
            // If input is empty, reset to the current page
            if (filter === '') {
                displayRows(currentPage);
                return;
            }
    
            // Search through the rows
            dataRows.forEach((row, index) => {
                const td = row.getElementsByTagName("td");
                for (let j = 0; j < td.length; j++) {
                    const txtValue = td[j].textContent || td[j].innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        displayRow = true;
                        break;
                    }
                }
                if (displayRow) {
                    row.style.display = "";
                    displayRow = false; // Reset for the next row
                }
            });
    
            // Update pagination to reflect the search results
            displayPagination();
        }
    
        // Event listener for the search input
        document.getElementById("myInput").addEventListener("input", searchTable);
    
        // Initially display header row and pagination
        headerRow.style.display = "";
        displayRows(currentPage);
        displayPagination();
    });
    
    Login or Signup to reply.
  2. The main problem is your displayRows function is affecting the visible and hidden rows from searchTable function.

    I slightly modified your code and added the pagination div since it’s not included in the snippet you provided.

    Here is the working code based on your requirement:

    document.addEventListener("DOMContentLoaded", function () {
        let currentPage = 1;
        let table = document.getElementById("myTable");
        const itemsPerPage = 5;
    
        document.getElementById("myInput").addEventListener("input", () => searchTable(true));
    
        function searchTable(fromInput) {
            var input, filter, table, tr, td, i, j, txtValue;
            input = document.getElementById("myInput");
            filter = input.value.toUpperCase();
            table = document.getElementById("myTable");
            tr = table.getElementsByTagName("tr");
            for (i = 1; i < tr.length; i++) {
                var displayRow = false;
                let txtValue = tr[i].innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    displayRow = true;
                }
                if (displayRow) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
            if (fromInput) currentPage = 1;
            displayPagination();
        }
    
        function displayPagination() {
            const filteredRows = document.getElementById("myTable").querySelectorAll("tr:not([style*='display: none']):not(.header)");
            const pageCount = Math.ceil((filteredRows.length) / itemsPerPage);
    
            showStart = (currentPage -1) * itemsPerPage;
            filteredRows.forEach(function(tr, index) {
    
                if (index < showStart || index >= showStart + itemsPerPage) {
                    tr.style.display = "none";
                }
            });
    
            const paginationDiv = document.querySelector(".pagination");
            paginationDiv.innerHTML = "";
    
            // Previous button
            const prevButton = document.createElement("button");
            prevButton.textContent = "Prev";
            prevButton.addEventListener("click", function () {
            if (currentPage > 1) {
                currentPage--;
                searchTable(false);
                updatePaginationButtons();
            }
            });
            paginationDiv.appendChild(prevButton);
    
            // Page buttons
            for (let i = 1; i <= pageCount; i++) {
            const button = document.createElement("button");
            button.textContent = i;
            if (i === currentPage) {
                button.classList.add("active");
            }
            button.addEventListener("click", function () {
                currentPage = i;
                searchTable(false);
                updatePaginationButtons();
            });
            paginationDiv.appendChild(button);
            }
    
            // Next button
            const nextButton = document.createElement("button");
            nextButton.textContent = "Next";
            nextButton.addEventListener("click", function () {
            if (currentPage < pageCount) {
                currentPage++;
                searchTable(false);
                updatePaginationButtons();
            }
            });
            paginationDiv.appendChild(nextButton);
        }
            
        function updatePaginationButtons() {
            const paginationButtons = document.querySelectorAll(".pagination button");
            paginationButtons.forEach((button, index) => {
            if (index === currentPage) {
                button.classList.add("active");
            } else {
                button.classList.remove("active");
            }
            });
        }
    
        searchTable(false);
    });
        <input
          type="text"
          id="myInput"
          placeholder="Search for names.."
          title="Type in a name"
        />
        <table id="myTable">
          <tr class="header">
            <th>#</th>
            <th style="width: 60%">Name</th>
            <th style="width: 40%">Country</th>
            <th style="width: 40%">Age</th>
            <th style="width: 40%">Email</th>
            <th style="width: 40%">Surname</th>
            <th style="width: 40%">Middlename</th>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Alfreds Futterkiste</td>
            <td>Germany</td>
            <td>31</td>
            <td>[email protected]</td>
            <td>Alfie</td>
            <td>Papa</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Berglunds snabbkop</td>
            <td>Sweden</td>
            <td>21</td>
            <td>[email protected]</td>
            <td>shy</td>
            <td>Mama</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Island Trading</td>
            <td>UK</td>
            <td>31</td>
            <td>[email protected]</td>
            <td>xerxe</td>
            <td>cici</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Koniglich Essen</td>
            <td>Germany</td>
            <td>54</td>
            <td>[email protected]</td>
            <td>naknak</td>
            <td>fiif</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Laughing Bacchus Winecellars</td>
            <td>Canada</td>
            <td>43</td>
            <td>[email protected]</td>
            <td>neknek</td>
            <td>pekpek</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Magazzini Alimentari Riuniti</td>
            <td>Italy</td>
            <td>23</td>
            <td>[email protected]</td>
            <td>hikhik</td>
            <td>hokhok</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>North/South</td>
            <td>UK</td>
            <td>32</td>
            <td>[email protected]</td>
            <td>tektek</td>
            <td>kita</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Paris specialites</td>
            <td>France</td>
            <td>65</td>
            <td>[email protected]</td>
            <td>tektek</td>
            <td>leklek</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Koniglich Essen</td>
            <td>Germany</td>
            <td>54</td>
            <td>[email protected]</td>
            <td>naknak</td>
            <td>fiif</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Laughing Bacchus Winecellars</td>
            <td>Canada</td>
            <td>43</td>
            <td>[email protected]</td>
            <td>neknek</td>
            <td>pekpek</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Magazzini Alimentari Riuniti</td>
            <td>Italy</td>
            <td>23</td>
            <td>[email protected]</td>
            <td>hikhik</td>
            <td>hokhok</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>North/South</td>
            <td>UK</td>
            <td>32</td>
            <td>[email protected]</td>
            <td>tektek</td>
            <td>kita</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Paris specialites</td>
            <td>France</td>
            <td>65</td>
            <td>[email protected]</td>
            <td>tektek</td>
            <td>leklek</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Koniglich Essen</td>
            <td>Germany</td>
            <td>54</td>
            <td>[email protected]</td>
            <td>naknak</td>
            <td>fiif</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Laughing Bacchus Winecellars</td>
            <td>Canada</td>
            <td>43</td>
            <td>[email protected]</td>
            <td>neknek</td>
            <td>pekpek</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Magazzini Alimentari Riuniti</td>
            <td>Italy</td>
            <td>23</td>
            <td>[email protected]</td>
            <td>hikhik</td>
            <td>hokhok</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>North/South</td>
            <td>UK</td>
            <td>32</td>
            <td>[email protected]</td>
            <td>tektek</td>
            <td>kita</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Paris specialites</td>
            <td>France</td>
            <td>65</td>
            <td>[email protected]</td>
            <td>tektek</td>
            <td>leklek</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Koniglich Essen</td>
            <td>Germany</td>
            <td>54</td>
            <td>[email protected]</td>
            <td>naknak</td>
            <td>fiif</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Laughing Bacchus Winecellars</td>
            <td>Canada</td>
            <td>43</td>
            <td>[email protected]</td>
            <td>neknek</td>
            <td>pekpek</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Magazzini Alimentari Riuniti</td>
            <td>Italy</td>
            <td>23</td>
            <td>[email protected]</td>
            <td>hikhik</td>
            <td>hokhok</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>North/South</td>
            <td>UK</td>
            <td>32</td>
            <td>[email protected]</td>
            <td>tektek</td>
            <td>kita</td>
          </tr>
          <tr>
            <td><input type="checkbox" name="name1" />&nbsp;</td>
            <td>Paris specialites</td>
            <td>France</td>
            <td>65</td>
            <td>[email protected]</td>
            <td>tektek</td>
            <td>leklek</td>
          </tr>
        </table>
        <div class="pagination"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search