Steps for Displaying Error Message when Search Result is Not Found in a JavaScript Table

After creating a table using HTML to display student data like name, degree, and profession, I added a search bar for users to find information on a specific student by typing the student's name. If the student is not in the table, a message "Result not found" is shown.

I've encountered two main issues: Firstly, the error message pops up even after typing just the first letter of the student's name. Secondly, even when entering the correct name listed in the table, the error message still appears.
My goal is for the error message to only appear if the name is not in the table.

let inputValue;
let input = document.getElementById("myInput");

// Function for handling search events
const search = (e) => {
  inputValue = input.value.toUpperCase();

  let tableEl = document.getElementsByTagName("table");
  let tr = tableEl[0].getElementsByTagName("tr");
  let th = document.getElementById("header")
  let no_result = document.getElementById("no_result");
  let container = document.querySelector(".container");

  for (let i = 1; i < tr.length; i++) {
    let dataValue = tr[i].getElementsByTagName("td")[0].textContent.toUpperCase(); 
    if (dataValue.includes(inputValue)) {
      console.log(inputValue);
      tr[i].style.display = ""; 
    }
    else if(inputValue.textContent !== dataValue){
      no_result.style.display="block" 
      tr[i].style.display = "none";
    }
  }
};

input.addEventListener("keyup", function (e) {
  search(e);
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.main {
  width: 100vw;
  height: 100vh;
  text-align: center;
  display: flex;
  flex-direction: column;
}

table,
th,
td {
  background-color: rgb(235, 139, 215);
  border: 1px solid black;
  border-collapse: collapse;
  font-size: 20px;
  text-align: center;
  padding: 20px;
  margin: 30px auto;
}

th {
  font-family: "Courier New", Courier, monospace;
}

tr,
td {
  font-family: "Lucida Sans", "Lucida Sans Regular", "Lucida Grande",
    "Lucida Sans Unicode", Geneva, Verdana, sans-serif;
}

input {
  width: 400px;
  padding: 20px;
  font-size: 20px;
  margin-top: 50px;
  border: 2px solid black;
  outline: none;
}

#no_result{
  width: 200px;
  height: 50px;
  align-self: center;
  display: none;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="main">
      <div>
        <input
          type="text"
          placeholder="Enter your name"
          id="myInput"
        />
      </div>
      <table id="myTable">
        <span id="no_result">
          <h2>No result found!!</h2>
    </span>
  
        <tr id="header">
          <th>Name</th>
          <th>Degree</th>
          <th>Profession</th>
        </tr>
        <tr>
          <td>John</td>
          <td>BSC-IT</td>
          <td>Full stack developer</td>
        </tr>
        <tr>
          <td>Tom</td>
          <td>BSC-IT</td>
          <td>Data Scientist</td>
        </tr>
        <tr>
          <td>Jerry</td>
          <td>Graphic Design</td>
          <td>Graphic Designer and animation</td>
        </tr>
        <tr>
          <td>James</td>
          <td>MCA</td>
          <td>Project Manager</td>
        </tr>
        <tr>
          <td>Roger</td>
          <td>BSC-IT</td>
          <td>Teacher</td>
        </tr>
      </table>>
      
    </div>

Below are key parts from my code regarding the issue mentioned. HTML

  <span id="no_result">
              <h2>No result found!!</h2>
        </span>
      

CSS

#no_result{
  width: 200px;
  height: 50px;
  align-self: center;
  display: none;
}

JAVASCRIPT This part displays the error message.


else if(inputValue.textContent !== dataValue){
      no_result.style.display="block" 
      tr[i].style.display = "none";

I would greatly appreciate any assistance!

Answer №1

This is a simplified snippet of code

Take note that thead and tbody are included, and hidden is used instead of display

let inputValue;
let input = document.getElementById("myInput");

// function triggered by an event
const search = (e) => {
  inputValue = input.value.toUpperCase();
  // console.log(inputValue);

  let tableEl = document.querySelector("table tbody");
  let tr = tableEl.querySelectorAll("tr");
  // let th = document.getElementsByTagName("th");
  let th = document.getElementById("header")
  let no_result = document.getElementById("no_result");
  let container = document.querySelector(".container"); // used to access hidden class

  tr.forEach(tr => {  // Accessing each row's name value
    let dataValue = tr.querySelector("td").textContent.toUpperCase(); 
    tr.hidden = !dataValue.includes(inputValue)
  })
  no_result.hidden = tableEl.querySelectorAll("tr[hidden]").length != tr.length;

};

input.addEventListener("keyup", function(e) {
  search(e);
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.main {
  width: 100vw;
  height: 100vh;
  /* display: grid;
  place-items: center; */
  /* margin: 0 auto; */
  /* background-color: black; */
  text-align: center;
  display: flex;
  flex-direction: column;
}

table,
th,
td {
  background-color: rgb(235, 139, 215);
  border: 1px solid black;
  border-collapse: collapse;
  font-size: 20px;
  text-align: center;
  padding: 20px;
  margin: 30px auto;
}

th {
  font-family: "Courier New", Courier, monospace;
}

tr,
td {
  font-family: "Lucida Sans", "Lucida Sans Regular", "Lucida Grande", "Lucida Sans Unicode", Geneva, Verdana, sans-serif;
}

input {
  width: 400px;
  padding: 20px;
  font-size: 20px;
  margin-top: 50px;
  border: 2px solid black;
  outline: none;
}

input:focus {
  outline: 2px solid gray;
}

#no_result {
  width: 200px;
  height: 50px;
  align-self: center;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <link rel="stylesheet" href="style.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
  <div class="main">
    <div>
      <input type="text" placeholder="Enter your name" id="myInput" autocomplete="off" />
    </div>

    <table id="myTable">
      <thead>
        <tr id="header">
          <th>Name</th>
          <th>Degree</th>
          <th>Profession</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>John</td>
          <td>BSC-IT</td>
          <td>Full stack developer</td>
        </tr>
        <tr>
          <td>Tom</td>
          <td>BSC-IT</td>
          <td>Data Scientist</td>
        </tr>
        <tr>
          <td>Jerry</td>
          <td>Graphic Design</td>
          <td>Graphic Designer and animation</td>
        </tr>
        <tr>
          <td>James</td>
          <td>MCA</td>
          <td>Project Manager</td>
        </tr>
        <tr>
          <td>Roger</td>
          <td>BSC-IT</td>
          <td>Teacher</td>
        </tr>
      </tbody>
    </table><span id="no_result" hidden>
          <h2>No result found!!</h2>
    </span>

    <div id="error4">

    </div>

    <!-- <div class="container hidden">
        <h1 ">Not found</h1>
      </div> -->
  </div>


  <script src="script.js"></script>
</body>

</html>

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

Using jQuery to dynamically insert an HTML element into a table

I'm trying to insert a hyperlink into an empty HTML table. This function works perfectly fine on Firefox and Chrome, taking only 0.2 seconds to load. However, when I try it on IE9, it takes at least 3 minutes to display the link. The issue seems to be ...

Python - Syntax Error - Unable to Locate Element by XPath

Attempting to gather all elements of a webpage with the assistance of Selenium web driver and utilizing XPATH. Each row that needs to be gathered commences with the same text. Therefore, the following code was implemented: container = driver.find_elements ...

I am looking to store individual objects in LocalStorage, however, I currently have the entire array saved

Struggling to figure out how to save a single object instead of the whole array when creating a movie watchlist. Clicking "add to watchlist" should save the single object in LocalStorage, while clicking "remove from watchlist" should remove it. I've a ...

Error: Unable to load L.GeometryField constructor in django-leaflet library

I'm having trouble saving a geolocation to a Postgres database using Django-leaflet. I keep getting an error message that says Uncaught TypeError: L.GeometryField is not a constructor. My code involves AJAX calls. <script> var csrftoke ...

Ways to share code across AngularJS frontend and Node.js backend

How can code be effectively shared between an AngularJS client and a Node.js server? After creating an AngularJS application, I now need to develop a RESTful server to provide data to the client. Some Angular services used on the client-side could also be ...

Creating camera shake in Three.js: A beginner's guide

I've been searching for hours online and I can't seem to figure this out. Is there any way to achieve this? If so, please share the steps with me. I found a code snippet but I'm unsure how to implement it properly. Can someone guide me on ho ...

What is the process for submitting a record to a table following the activation of a JavaScript link or button

I am working on creating a like-unlike button below each post for registered users to interact with. I have successfully created the button itself, but now I need to figure out how to store records when a user clicks the button. My idea is to utilize a tab ...

Restrictions on webpage components within code

Is there a maximum limit to the number of HTML elements that a webpage can load on a browser without including CSS or scripts? ...

There was a TypeError encountered in angular-highcharts, stating that it is not possible to read the property '0' of an undefined

Currently, I am utilizing the angular5 framework in conjunction with the angular-highcharts library to generate a basic map based on the highcharts demonstration available at https://www.highcharts.com/maps/demo/category-map. Here is a snippet of the code: ...

Improve the nested async callback in the componentDidMount() function of a React component by moving it to a separate

My current approach involves utilizing react's componentDidMount(), which contains a substantial amount of code and performs two callbacks. Eventually, within the innermost callback (the second one), I trigger this.setState({}). Simplified Code clas ...

"Utilizing AngularJS to asynchronously send an HTTP POST request and dynamically update

I've been working on an angularjs chat module and have come across a challenge. I developed an algorithm that handles creating new chats, with the following steps: Click on the 'New Chat' button A list of available people to chat with wil ...

Display the remainder of an image's height within a div container

Here is the code snippet I am working with: HTML: <div id="mapWrapper" style="height: 624px;"> <div class="box" id="map"> <h1>Campus</h1> <p>Description Campus Map.</p> <img src="abc.png" ...

Having difficulty utilizing Objects.key.map() for mapping purposes

I'm struggling to display my cart status in a JSX table and facing challenges. The state Chrome Console shows this Object output: { "cartItems": { "5": { "id": 5, "name": "Aut assumenda.", "price": 526, "quantity": 1, ...

Enhance the readability and writability of the properties of JavaScript objects

I'm curious if there's a way to make existing properties of JavaScript objects immutable after they've been assigned. Essentially, what I want is to lock in the current properties of an object but still allow new ones to be added. Can exis ...

The process of styling with styled components in Mui - a guide to styling

Currently, I am facing challenges with styling and organization while working on a new react project with material ui and styled components. Despite researching best practices for styled components, I am still struggling to find an effective solution for s ...

What is the best way to pass createdDt and updatedDat values in an Angular form without displaying them on the template?

I am working on a message creation form in Angular where I need to include createdDt and updatedDt as hidden values. These values should not be visible in the template. I want to automatically set the current date and time for both createdDt and updatedD ...

Angular: The function t(...) does not support success - TypeError

My code is generating the error TypeError: t(...).success is not a function. I have tried searching for a solution but haven't been able to figure out why this error is happening in my specific case. Here is a snippet of my JS code. Can anyone point ...

Is there a way for my JavaScript file to manipulate an EJS variable?

In the index.ejs file, I declared an ejs variable named "complete" which verifies whether a user has completed a journal entry by using the following code: <% if (complete == false) { %> <button class="new_journal">Fill Out Journal<i cla ...

After implementing AXIOS, don't forget to refresh the static content in VUE

I'm encountering some issues with Vue.js: Currently, I have a list of elements that I'm iterating through using v-for in my script. This array is retrieved from Axios (API) in the created() lifecycle hook. Additionally, I have a static variable ...

Having trouble with your GitHub Pages site displaying properly on desktop but working fine on mobile?

I am facing an issue with my GitHub pages site on a custom domain. It works perfectly fine on mobile, but when I try to access the same URL from desktop, I encounter a DNS_PROBE_FINISHED_NXDOMAIN error. Any suggestions on why this might be happening? You c ...