The search functionality is malfunctioning within the JavaScript table

I am working with a table that I want to filter based on input values. However, the current filtering function is not working as expected. I have utilized an onkeyup function for the filtering process. For more details and a live example, check out the jsfiddle link provided below.

function filterTable() {
    var input = document.getElementById("tabFilter");
    var value = input.value.toLowerCase();
    var rows = document.getElementsByTagName("tr");
    var matches = 0;
    for (var i = 0; i < rows.length; i++) {
        var fullname = rows[i].getElementsByTagName("td")[0].innerHTML.toLowerCase();
        if (fullname) {
            if (value.length == 0 || 
                (value.length < 3 && fullname.indexOf(value) == 0) || 
                (value.length >= 3 && fullname.indexOf(value) > -1)) {
                rows[i].style.display = "";
                matches++;
            } else {
                rows[i].style.display = "none";
            }
        }
    }
    var noResultsMsg = document.getElementById("noresults");
    if (matches === 0 && noResultsMsg) {
        noResultsMsg.style.display = "";
        document.getElementById("qt").innerHTML = value;
    } else {
        noResultsMsg.style.display = "none";
    }
}

Check out the jsfiddle demo here

Answer №1

  1. It's recommended to utilize textContent over innerHTML since innerHTML may also select HTMLElement
  2. Set index as 2 instead of filtering at the 0th index, where there is no name column present
  3. Include fullname && condition as well
  4. Ensure that the condition if (fullname.length) { precedes accessing its index element.

var obj = [{
  Firstname: "Bob",
  Lastname: "Mayer",
  Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c6e636e4c616d75697e226f6361">[email protected]</a>",
  Number: "123456789"
}, {
  Firstname: "Steven",
  Lastname: "Spil",
  Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="374443524152597744475e5b5b1954585a">[email protected]</a>",
  Number: "987654321"
}, {
  Firstname: "Paul",
  Lastname: "Taucker",
  Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="acdccdd9c0ecd8cdcfc782cfc3c1">[email protected]</a>",
  Number: "578954321"
}, {
  Firstname: "computer",
  Lastname: "Tech",
  Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="50333f3d2010243533387e333f3d">[email protected]</a>",
  Number: "418741876"
}, {
  Firstname: "User",
  Lastname: "Interface",
  Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9aefe9ffe8daf3f4eeffe8b4f3f4">[email protected]</a>",
  Number: "949796928"
}];

var editCounter = 0;

var table = document.createElement('table');
table.id = "table";

var headcell = document.createElement('th');
var cell = document.createElement('td');
var input = document.createElement('input');

var tableContainer = document.createElement('div');
document.body.appendChild(tableContainer);

var filter = document.createElement('input');
filter.type = "text";
filter.placeholder = "Filter";
filter.id = "tabFilter";
filter.setAttribute("onkeyup", "filterTable()");
tableContainer.appendChild(filter);

var formContainer = document.createElement('form');
formContainer.id = "details";
document.body.appendChild(formContainer);

function createTable() {

  tableContainer.appendChild(table);
  var row = document.createElement('tr');
  table.appendChild(row);

  headcell = document.createElement('th');
  row.appendChild(headcell);
  headcell.innerHTML = "Select";

  headcell = document.createElement('th');
  row.appendChild(headcell);
  headcell.innerHTML = "Sl.No";

  Object.keys(obj[0]).forEach(function(val) {
    headcell = document.createElement('th');
    row.appendChild(headcell);
    headcell.innerHTML = val;
  });

  for (var i = 0; i < obj.length; i++) {

    var btnSave = document.createElement('button');
    btnSave.innerHTML = "Save";

    var btnEdit = document.createElement('input');
    btnEdit.type = "button";
    btnEdit.value = "Edit";

    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = "checkBox";

    var row = document.createElement("tr");
    table.appendChild(row);

    var cell = document.createElement("td");
    row.appendChild(cell);
    cell.appendChild(checkbox);

    var cell = document.createElement("td");
    row.appendChild(cell);
    cell.innerHTML = i;

    for (key in obj[i]) {
      var cell = document.createElement("td");
      row.appendChild(cell);
      cell.innerHTML = obj[i][key];
    }
  }
  return true;
}
createTable();

function filterTable() {
  var q = document.getElementById("tabFilter");
  var v = q.value.toLowerCase();
  var rows = document.getElementsByTagName("tr");
  var on = 0;
  for (var i = 0; i < rows.length; i++) {
    var fullname = rows[i].getElementsByTagName("td");
    if (fullname.length) {
      fullname = fullname[2].textContent.toLowerCase();
      if (fullname && v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1)) {
        rows[i].style.display = "";
        on++;
      } else {
        rows[i].style.display = "none";
      }
    }
  }

}
* {
  font-family: 'verdana'
}
table {
  margin-bottom: 15px
}
input {
  margin: 5px
}
th,
td {
  border: 1px solid #ccc;
  font: 13px'verdana';
  padding: 5px
}
th {
  font-weight: bold
}
table [type="text"],
table [type="email"],
table [type="number"] {
  display: block;
  width: 90px
}
[value="Delete"],
[value="Copy"] {
  display: block
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to integrate nano.uuid into a series of promises that are fetching data from the database?

When working with express routing and nano, I encountered a challenge: router.get('/', function (request, response) { db.view('designdoc', 'bydate', { 'descending': true }) .then(results => { // data ...

What is the process for transforming JSON into a different format?

Currently, I have a JSON array structured as follows: var data = { report: [ { Name: "Nitin", comment: [ { count: 0, mName: "Feb" }, ...

Error: Unable to locate the include file

Hello, I am currently a student working on a project where I am attempting to retrieve a list of books from the server and display them one by one using ejs. Here is an overview of my project structure: | |-----routes | |-----index.js |-----vie ...

What is the reason behind encountering these errors while trying to run my Gatsby development server?

I'm currently working on the part three tutorial provided by Gatsby on their official website and I've encountered a problem. Upon executing the command gatsby new tutorial-part-three https://github.com/gatsbyjs/gatsby-starter-hello-world I rec ...

A guide on identifying the data type of a value entered into an HTML table using JavaScript

Currently, I am tackling a contenteditable HTML table challenge. My goal is to enforce the insertion of only numeric values while alerting the user if they attempt to input strings or non-numeric characters. Can anyone provide guidance on how to achieve th ...

cross-domain ajax response

Imagine a unique scenario that will pique the interest of many developers. You have a JavaScript file and a PHP file - in the JS file, you've coded AJAX to send parameters via HTTP request to the PHP file and receive a response. Now, let's delve ...

Error: Angular - encountering undefined response when making HTTP request

When making a HTTP GET request to my backend, it returns the following JSON data: "{\"instID\":\"2018#10#30\",\"procID\":1161006,\"threadNum\":0,\"status\":2}", "{\"instID\":\"2018#1 ...

3 Methods for Implementing a Floating Header, Main Content, and Sidebar with Responsive Design

I am following a mobile-first approach with 3 containers that need to be displayed in 3 different layouts as shown in the image below: https://i.sstatic.net/UjKNH.png The closest CSS implementation I have achieved so far is this: HTML: <header>.. ...

Conducting various calculations and showcasing them all on a single webpage

Uncertain about what to name this, but let's see if you understand my question. I have a table on a standard HTML page and I am performing some calculations using Javascript/jQuery. Example: function addThem() { var result; result = userIn ...

Inconsistencies in spacing between shapes bordering an SVG Circle using D3.js are not consistent across platforms

After creating a SVG circle and surrounding it with rectangles, I am now attempting to draw a group of 2 rectangles. The alignment of the rectangle combo can either be center-facing or outside-facing, depending on the height of the rectangle. However, I am ...

Angular: facing difficulty displaying static html pages on server, although they render correctly when run locally

Within my Angular project, I have stored a few static html files (specifically sampleText.html) in the src/assets/html folder. In one of my components, I am attempting to fetch and display this file. The following code is being used for this purpose. Every ...

Utilizing HTML to call a function and fetching data from AngularJS

I've been struggling to retrieve the value after calling a function in my HTML file. Despite trying various methods after conducting research, I have not achieved success yet. Take a look at the code below: HTML: <div class="form-group"> & ...

How to toggle two classes simultaneously using JQuery

Check out this code snippet: http://jsfiddle.net/celiostat/NCPv9/ Utilizing the 2 jQuery plugin allows for the following changes to be made: - The background color of the div can be set to gray. - The text color can be changed to red. The issue arises wh ...

Seamless Integration of jQuery Functions

I am in need of some assistance with passing a chain of jQuery methods into a function as an argument. The goal is to have dynamic methods executed on a DOM object. This functionality would be particularly useful for writing qUnit tests where centralizat ...

When attempting to set up a build task in VSCODE by clicking the configure button, I encountered an issue where nothing

Whenever I try Ctrl+shift+B, nothing happens. Even after creating a .vscode folder with a tasks.json file inside, VScode still doesn't respond. I'm expecting to see the menus pop up like in other posts, but mine just seems stuck. Any help would b ...

Is there a way to halt the polling process for the specific API handling the background task?

I have been using this polling function for executing background tasks. export const poll = ({ fn = () => {}, validate = (result) => !!result, interval = 1000, maxAttempts = 15, }) => { let attempts = 1; // eslint-disable-next-line con ...

How to activate a function or event upon closing a browser tab with JavaScript

How can a function be triggered when a user closes the browser tab, preventing it from closing immediately and instead displaying a popup prompting the user to either proceed to another page or close the tab? Scenario: In the event that a user attempts t ...

Ways to have a div show up and stay in place as you scroll down?

How can I make the div "full" sticky after scrolling down 200px, and revert to display none when scrolling back up? Is there a way to accomplish this using JavaScript? In the code snippet below, you will find three divs: header, header2, and header3. The ...

Can you explain the difference between CDN and ESM builds in vue.js?

According to the Vue.js documentation, there are differences in syntax depending on whether you are using the CDN or ESM build of Vue.js. What is the significance of having two different builds and how does it result in a difference in usage syntax? Infor ...

Error: Unable to find the transport method in Socket.io

I recently implemented user side error logging on my website to track errors. I have noticed that sometimes it logs a specific error related to socket.io code: TypeError: this.transport is undefined This error seems to only occur for users using Firefox ...