Conceal all elements until a search query is entered using the search bar

I want to create a search bar that hides all elements until the user actually searches for them, you can check out my JSfiddle for reference: `JSfiddle Link

    <div id="search">
              <form>
  <input type="text" name="search" id="myInput" onkeyup="mFunction()" 
   placeholder="Search ?..">
 </form>
 <nav>
 <table id="myTable">
 <tr class="header">
<th style="width:500px;">Question</th>
</tr>
<tr>  
 <td onclick="window.location.href='#web'">What is the company email?</td>
</tr>
 <tr>
<td onclick="window.location.href='#web'">Is the website currently under 
development?</td>
 </tr>
 <tr>
<td onclick="window.location.href='#game'">Why are the games not working 
online?</td>
  </tr>
 <tr>
  <td onclick="window.location.href='#game'">What is the next game or games 
 that you are working on?</td>

</tr>

<tr>
 <td onclick="window.location.href='#game'">Are you working on Modern Jewels 
 anymore?</td>
</tr>
  <tr>
<td onclick="window.location.href='#game'">What are the controls for Modern 
 Jewels?</td>
    </tr>
 </table>
 </div>
 </nav>`

JavaScript/jQuery

    function mFunction() {
  // Declare variables 
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search 
  query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
}

I am in need of assistance for a FAQ page where users can search for questions without being overwhelmed by a large list of questions. Any help would be greatly appreciated! :D

Answer №1

With all the search results neatly displayed in the table, you have the flexibility to manipulate the entire table by utilizing jQuery's .hide() and .show() animations.

If you want to hide the table until the user performs a search, simply use .hide() as shown below:

$("#myTable").hide();

Answer №2

To implement a search functionality on your table, you can listen for the keyup event in your search input. If the input value is empty, hide the entire table; otherwise, show only the td elements in the table that contain the search term.

$('table').hide();
$('#myInput').on("keyup", function(){
    var searchVal = $('#myInput').val();
    if(searchVal == ""){
        $('table').hide();
    }
    else{
        $('table').show();
        $('table tr td').show();
        $('table tr td:not(:contains("' + searchVal + '"))').hide();
    }
});

Check out the demo here: https://jsfiddle.net/p90uwdg7/

By default, this search is case sensitive. If you want to make the search case insensitive, you can override the contains function as shown below:

jQuery.expr[':'].contains = function(a, index, obj) {
  return jQuery(a).text().toUpperCase()
      .indexOf(obj[3].toUpperCase()) >= 0;
};

Check out the updated demo here: https://jsfiddle.net/p90uwdg7/1/

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

Is there a way to convert the text within a div from Spanish to English using angular.js?

I am working with a div element that receives dynamic text content from a web service in Spanish. I need to translate this content into English. I have looked into translation libraries, but they seem more suited for individual words rather than entire dyn ...

Execute JavaScript function after completion of CSS animation using jQuery

I'm working on an accordion feature that uses CSS animation to expand the clicked item. The expansion is triggered by li:target. However, I'm facing an issue where when clicking on an item, the scroll position doesn't align correctly with t ...

The medium-zoom feature is currently experiencing issues with functionality within Angular version 13

I've been attempting to incorporate medium-zoom functionality into my project using https://www.npmjs.com/package/medium-zoom Here are the steps I took: ng new medium_zoom_test (Angular 13) with routing & css npm install medium-zoom The image is ...

The event listener activates multiple times on HTML pages that are dynamically loaded with AJAX

Javascript utility function: // This event listener is set using the on method to account for dynamic HTML $(document).on('click', '#next_campaign', function() { console.log('hello'); }); Website layout: <script src=&q ...

Unable to proceed, WISTIA upload frozen at 100% complete

I recently integrated the Wistia API for video uploads. Everything seemed to be working fine as per the Wistia documentation until I encountered an issue. After uploading a video file, the progress bar would reach 100%, but then an error was logged in the ...

Displaying a form within an iframe

I am trying to embed a form within an iframe that will load on a random page when the user clicks a bookmarklet. Below is the code snippet I have written so far: loginForm = document.createElement("form"); loginForm.setAttribute("method","Post"); ...

Pass the output of one function as an argument to another function in a Node.js Express application

I'm having trouble retrieving the value declared in the first function CreateTag and using it as a variable in the second function CreateStream. Despite working with nodejs Express, I've attempted to use RETURN without success. I've tried v ...

What is the process for creating two columns with an input box beneath them?

I am facing a challenge with my code. I am struggling to create the desired design where there are two columns and below them an input box that will be displayed when a button is pressed. The design I am aiming for can be viewed here: enter image descripti ...

Generating alternate list items

I'm attempting to design a list style that resembles the one depicted in the image linked below: https://i.stack.imgur.com/U7vMw.jpg My issue is that when I try to add borders, they end up applying to the entire structure. .styled-list { list-st ...

Can you explain the intended function of .reference in the CSS code provided?

Currently delving into some sample HTML from codrops. I came across the following CSS styling. After scouring the web, it seems others have used span.reference, but I can't seem to grasp the purpose of .reference. Any insights would be much appreciat ...

Using AngularJS, I can bind the ng-model directive to asynchronously update and retrieve data from

I am currently working with Angular to develop a preferences page. Essentially, I have a field in a mysql table on my server which I want to connect my textbox to using ng-model through an asynchronous xhr request for setting and fetching data. I attempt ...

Issue with transferring JQuery variable to JavaScript

Using JQuery, I am attempting to retrieve a variable from PHP located at a specific URL and then utilize that variable in JavaScript to modify the content on the webpage. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">& ...

A guide on how to mention users in Discord.js

I attempted to get the bot to mention a member using @, but when I used message.channel.send(<@id>+"text") it showed an error message saying unexpected sign '<'. Is there a way to successfully mention members with the bot? ...

Help me understand how to display the data in a JSON array

{ "entries": [ { "id": 23931763, "url": "http://www.dailymile.com/entries/23931763", "at": "2013-07-15T21:05:39Z", "message": "I ran 3 miles and walked 2 miles today.", "comments": [], "likes": [], ...

Only consider valid values for input and ignore any zeros

I am working on a form where I need to accept any number, regardless of if it's negative, a float, or a long integer. I have implemented code to not allow null, undefined, or empty values, but I encountered an issue where entering 0 is being read as e ...

Issue with the successful execution of connection event handler in NodeJS and Socket.io?

When I look at my code in files named server.js and index.html, I notice that the io.on('connection') part is not executing the console.log method in its callback when I visit my server in the web browser. Take a look at the code snippets below ...

The grid fails to apply remote filtering values when an additional Nested ajax call is incorporated alongside the current HttpProxy configuration

Whenever I click for filter/sort for remote filtering, Forms.asp triggers using a proxy and automatically reloads. Previously, when I used the script below to reload the ExtJS grid with Forms.asp returning new XML with filtered grid data, everything worked ...

When deciding between .attribute=, setAttribute, and attr(), which is the best option to use?

.attribute in Javascript let friendDiv = document.getElementById("friend"); friendDiv.className = "list"; VS setAttribute in Javascript let friendDiv = document.getElementById("friend"); friendDiv.setAttribute("class","list"); VS .attr in Jquery $(" ...

execute a retrieval query on an html pop-up

I have recently created an HTML web resource that I am displaying when a ribbon button is clicked. Within this popup, there is a dropdown list that I intend to fill with records obtained through a fetchXml query. The issue I'm encountering is that de ...

Having trouble finding the correct route using an ajax request

Having trouble finding the correct route through an ajax call In my view, I have 2 HTML buttons that are generated using PHP <?php if ($comment_exist == null): ?> <p><input type ="button" id = "sb" value="I Comment"></p> &l ...