Search for specific data within a table while still keeping the left header column in

I have a table with a fixed left column and I am trying to implement a search function that will show the specific column, not row.

So far, I have only come across a solution that displays the row: How to perform a real time search and filter on a HTML table

However, since my headers are in the column, this method is not very effective.

By the way, I am fairly new to JavaScript, so please bear with me.. :p

You can view my codepen to see what I am attempting to achieve. http://codepen.io/genemiester/pen/qZrpgZ

var $rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

$rows.show().filter(function() {
    var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
    return !~text.indexOf(val);
}).hide();
});

Is my issue clear? Thank you in advance for any assistance!

Answer №1

New and Improved Filter:
Easily filter data just like in the screenshot provided.

I made some enhancements to the JS Code, changing from Table to Div, along with some CSS modifications.
Be sure to check out the demo for a live preview.

$(document).ready(function() {
    $("#clearsearch").click(function() {
        $("#clearsearch").fadeOut(300);
        $("#search").val("");
        $("#contentsearch div span").removeClass('success');
        $("#contentsearch div").removeClass('hide');
    });
    $("#search").keyup(function() {
        var result = $(this).val().replace(/ +?/g, "").toLowerCase();
        if (result != null && result != "") {
            $("#clearsearch").fadeIn(300);
            $("#contentsearch div").addClass('hide');
            $("#contentsearch div").find('span').each(function() {
                var tbresult = $(this).text().replace(/ +?/g, "").toLowerCase();
                if (tbresult.indexOf(result) !== -1) {
                    $(this).closest('div').removeClass('hide');
                    $(this).addClass('success');
                } else {
                    $(this).removeClass('success');
                }
            });
        } else {
            $("#clearsearch").fadeOut(300);
            $("#contentsearch div").removeClass('hide');
            $("#contentsearch div span").removeClass('success');
        }
    });
});
.gap{ height: 10px;}
.hide{dispaly: none;}
#search{ padding-right: 15px;}
.form-group span{ position: relative; left: -24px; top: 3px; cursor: pointer; display: none;}
.form-group span:hover{ color: red;}
.success{
  background-color: #dff0d8;
}
.tableheads, #contentsearch div{
  border: 1px solid #ddd;
 box-shadow: 1px 0px 0px 0px rgba(221,221,221,1);
  float: left;
  display: inline-block;
}
.tableheads span, #contentsearch div span{
  padding: 8px;
  display: block;
  float: none;
  border-bottom: 1px solid #ddd;
}
.tableheads span{
  background-color: #f5f5f5;
}
.no-border-bottom{
  border-bottom: none !important;
}
.no-border-right{
  border-right: none !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="clearfix gap">
    </div>
    <div class="form-inline">
      <div class="form-group">
        <label>Search :
        </label>
        <input type="text" class="form-control" name="search" id="search" placeholder="Search">
        <span id="clearsearch" class="glyphicon glyphicon-remove">
        </span>
      </div>
    </div>
    <div class="clearfix gap">
    </div>
    <div class="tableheads no-border-right">
      <span>Name
      </span>
      <span>State
      </span>
      <span class="no-border-bottom">Location
      </span>
    </div>
    <div id="contentsearch">
      <div class="no-border-right">
        <span>John
        </span>
        <span>Telangana
        </span>
        <span class="no-border-bottom">Hyderabad
        </span>
      </div>
      <div class="no-border-right">
        <span>Nathaniel
        </span>
        <span>Andhrapradesh
        </span>
        <span class="no-border-bottom">Vijag
        </span>
      </div>
      <div class="no-border-right">
        <span>Charles
        </span>
        <span>Tamilnadu
        </span>
        <span class="no-border-bottom">Chennai
        </span>
      </div>
      <div class="no-border-right">
        <span>Christian
        </span>
        <span>Karnataka
        </span>
        <span class="no-border-bottom">Bangalore
        </span>
      </div>
    </div>
    <div class="clearfix gap">
    </div>
  </div>
</div>

Demo with Table Search Feature:
Experience the previous demo showcasing table search functionality.

$(document).ready(function() {
    $("#clearsearch").click(function() {
        $("#clearsearch").fadeOut(300);
        $("#search").val("");
        $("#tablecontent tbody tr td").removeClass('success');
        $("#tablecontent tbody tr").removeClass('hide');
    });
    $("#search").keyup(function() {
        var result = $(this).val().replace(/ +?/g, "").toLowerCase();
        if (result != null && result != "") {
            $("#clearsearch").fadeIn(300);
            $("#tablecontent tbody tr").addClass('hide');
            $("#tablecontent tbody tr").find('td').each(function() {
                var tbresult = $(this).text().replace(/ +?/g, "").toLowerCase();
                if (tbresult.indexOf(result) !== -1) {
                    $(this).closest('tr').removeClass('hide');
                    $(this).addClass('success');
                } else {
                    $(this).removeClass('success');
                }
            });
        } else {
            $("#clearsearch").fadeOut(300);
            $("#tablecontent tbody tr").removeClass('hide');
            $("#tablecontent tbody tr td").removeClass('success');
        }
    });
});
.gap{ 
    height: 10px;
}
.hide{ 
      dispaly: none;
}
#search{ 
      padding-right: 15px;
}
.form-group span{ 
      position: relative; 
      left: -24px; 
      top: 3px; 
      cursor: pointer; 
      display: none;
}
.form-group span:hover{ 
      color: red;
 }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
   <div class="row">
      <div class="clearfix gap"></div>
      <div class="form-inline">
         <div class="form-group">
            <label>Search :</label>
            <input type="text" class="form-control" name="search" id="search" placeholder="Search">
            <span id="clearsearch" class="glyphicon glyphicon-remove"></span>
         </div>
      </div>
      <div class="clearfix gap"></div>
      <table id="tablecontent" class="table table-bordered">
         <thead>
            <tr class="active">
               <th>S.No.</th>
               <th>Name</th>
               <th>Country</th>
               <th>Location</th>
            </tr>
         </thead>
         <tbody>
            <tr>
               <td>1</td>
               <td>John</td>
               <td>India</td>
               <td>Hyderabad</td>
            </tr>
            <tr>
               <td>2</td>
               <td>Nathaniel</td>
               <td>India</td>
               <td>Mumbai</td>
            </tr>
            <tr>
               <td>3</td>
               <td>Charles</td>
               <td>India</td>
               <td>Pune</td>
            </tr>
            <tr>
               <td>4</td>
               <td>Christian</td>
               <td>India</td>
               <td>Secunderabad</td>
            </tr>
         </tbody>
      </table>
   </div>
</div>

Answer №2

Give this code a try, it may be just what you were looking for

var $rows = $('table tbody tr');
$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

  var regex = new RegExp(escapeRegExp(val));

  $rows.show().filter(function() {
    var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
    return !text.match(regex);
  }).hide();
});

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="search">

<table>
  <tbody>
    <tr>
      <td>google</td>
      <td>Bing</td>
      <td>Search Engine</td>
    </tr>


    <tr>
      <td>Opera</td>
      <td>Chrome</td>
      <td>FireFox</td>
    </tr>
  </tbody>
</table>

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

The Aurelia application encounters a "Maximum call stack size exceeded" error while trying to bind FullCalendar

I am currently working on setting up a JQuery plugin (FullCalendar) within my Aurelia application, which is built using TypeScript. I am relatively new to web development and just trying to get a basic example up and running. To start off, I utilized this ...

Tips for automatically updating a start and end page input field

In my project, I am working with a list of start and end page numbers using angularJS forms. One specific feature I want to implement is the automatic updating of start page values based on the previous end page. For example, if a user enters '4' ...

Failure in Bootstrap Typography #1 - Unable to locate proper class attribute values for uppercase and reverse transformations

<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel= ...

An HTML form featuring various submit buttons for accomplishing different tasks

After searching extensively, I have come across solutions that are similar but not quite right for my specific situation. Here's what currently works for me: <script type="text/javascript"> function performTask1(a, b) { window.open('intern ...

Error: bundling unsuccessful: Issue occurred while attempting to locate module `react-native-vector-icons/Feather`

Implementing a Flatlist from the React Native library in my React Native project. Managed to install all necessary libraries. package.json "dependencies": { "feather-icons-react": "^0.3.0", "react": "16.6.3", "react-native": "0.57.8", " ...

Changing Enum Value to Text

In my enum file, I have defined an object for PaymentTypes: export enum PaymentTypes { Invoice = 1, CreditCard = 2, PrePayment = 3, } When I fetch data as an array from the database, it also includes PaymentType represented as numbers: order: ...

Utilizing the designated link name

As part of my program, I have to generate hyperlinks for each row in a MySQL table. To accomplish this, I used the C MYSQL API to fetch the data from the table: while ((row = mysql_fetch_row(result))) { ....//some code to print the data.... } I am ab ...

Generating HTML code in Java to incorporate a background image

After creating an HTML string, I find myself needing to assign a background image. protected void onPostExecute(HashMap<String,String> hPlaceDetails){ String backgroundImage = ?????? String name = ...

Error Alert: Duplicate Status Detected While Posting on Twitter via API

I am delving into the world of JavaScript for the first time and using Node.js in conjunction with the Twitter API to enhance my coding skills. To facilitate this learning process, I have incorporated the Twit NPM package into my project. My goal is to dev ...

Tips on choosing the initial nested element

Currently, I am working with cheerioJS, a library that shares selectors with JQuery. Given this, my query pertains to JQuery. In my HTML code, there are nested span tags where arbitrary tags may be present between them. For example: <span> <p&g ...

React fullpage.js causing z-index stacking problems

Take a look at the demo here: I'm having trouble getting the 'more info' modal to display above all other elements on the screen. Here's the desired stacking order, with the highest stacked element listed first: modal nav open header ...

Access the angular controller using the radio button option

I am looking to showcase data in an HTML table retrieved from an Angular controller. I have the controller set up but I am unsure about how to display the data when a radio button is selected. <div class="radio"> <label class="radio-inline" ...

The styled components can create identical CSS classes with varying conditions

Below are the CSS styles I am currently using: import styled, { css } from "styled-components"; const H4 = css` font-family: "Futura"; font-style: normal; font-weight: 500; font-size: 20px; line-height: 140%; color: #3a786a ...

What is the best way to increase the value of a variable using jQuery?

As I work on adding dates to a slider, I find myself needing to increment the values with each click. Initially, I start with the year - 2. $('#adddates').click(function() { var year = 2; $("#slider").dateRangeSlider({ bounds: { ...

Blinking Effect of New Element in JQuery ListView

I'm attempting to implement AJAX functionality in a JQuery listview that will make flash yellow, but unfortunately I am having trouble getting it to work. Could someone provide me with some guidance? http://jsfiddle.net/zFybm/ ...

Creating thumbnails for documents, like in Google Docs, using NextJS

For my personal project, I am working on creating a Google Docs clone using Quill and NextJS. As part of this project, I want to have thumbnails for all the documents displayed, similar to Google Docs. I initially tried displaying the first 100 characters ...

Using jQuery with the "include" tag in Django templates

I'm attempting to reduce the redundancy of repeatedly appending the same div. When using ajax and attempting to pass a context to another file after each successful post, I keep encountering TemplateSyntaxError. TemplateSyntaxError at /items/order/254 ...

Set up four divs in a cascading arrangement across four separate columns

Looking to set up 4 cascading divs that create the appearance of being in 4 columns. Here is the given html structure (unable to be modified) <div class="col1"> 1111 <div class="col2"> 2222 <div cl ...

Ensure there is a gap between each object when they are arranged in a

Is there a way to customize the layout of elements in the ratings view so that there is automatic spacing between them? I considered using text (white spaces) for this purpose, but it seems like an inefficient solution. Are there any other alternatives to ...

While using the Android Firefox browser, I noticed that the keyboard is causing my screen to shrink in size

As I work on creating a cross-platform HTML page, I have encountered an issue with text fields on Android smartphones. When I attempt to type in a text box, the keyboard pops up and causes my HTML page to shrink within the viewport. I'm curious to kn ...