How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows:

name   |    date     |   agencyID
test      2016-03-17     91282774
test      2016-03-18     27496321

My goal is to have a dropdown menu containing all the 'agencyID' values, and when a specific ID is selected, only display the table rows with that corresponding agencyID. I already have a search functionality using an input type text.

The current search function operates like this, but I would like to achieve similar results using a select dropdown:

(function ($) {

    $('#filter').keyup(function () {

        var rex = new RegExp($(this).val(), 'i');
        $('.searchable tr').hide();
        $('.searchable tr').filter(function () {
            return rex.test($(this).text());
        }).show();

    })

}(jQuery));

I am open to exploring the possibility of utilizing angularJS if it offers a more efficient solution

Answer №1

Make sure to include a change handler on the select dropdown.

Here is the HTML code:

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>

<select id="filter">
  <option value="">Choose a filter</option>
  <option value="1231423424">1231423424</option>
  <option value="456456e54">456456e54</option>
  <option value="123488745">123488745</option>
</select>

<table id="searchable">
  <tr>
    <th>name</th>
    <th>date</th>
    <th>agencyID</th>
  </tr>
  <tr>
    <td>test 1</td>
    <td>date 1</td>
    <td>1231423424</td>
  </tr>
  <tr>
    <td>test 2</td>
    <td>date 2</td>
    <td>456456e54</td>
  </tr>
  <tr>
    <td>test 3</td>
    <td>date 3</td>
    <td>456456e54</td>
  </tr>
  <tr>
    <td>test 4</td>
    <td>date 4</td>
    <td>123488745</td>
  </tr>
  <tr>
    <td>test 5</td>
    <td>date 5</td>
    <td>123488745</td>
  </tr>
</table>

Javascript code:

$(document).ready(function(){

    $('#filter').change(function(){

    var filterValue = $(this).val();
    if(filterValue==""){
        $("#searchable tr").show();
    } else{
      $("#searchable tr").hide();
      $("#searchable td:nth-child(3)").each(function(){
        if( $(this).text() == filterValue){
          $(this).parent().show();
        }
      });
    }
  });

});

View it in fiddle

Answer №2

Check out this different approach utilizing the :contains() selector:

$select.on('change', function(){
    $('.highlight').removeClass('highlight');
    var id = $(this).val();
    $('table').find("tr:contains('"+id+"')").addClass('highlight');
  });

View the live example here

Answer №3

you have the option to assign an id to tr representing the agency

<select id="select">
<option value=""></option>
<option value="91282774">91282774</option>
<option value="27496321">27496321</option>
</select>

<table id="mytable">
<tr><th>name</th><th>data</th><th>agency</th></tr>
<tr id="91282774"><td>test</td><td>2016-03-17</td><td>91282774</td></tr>
<tr id="27496321"><td>test</td><td>2016-03-18</td><td>27496321</td></tr>
</table>

and then search for the id when the selection changes

$(document).ready(function(){

  $("#select").change(function(){
    var value = $(this).val();
    if(value == "")
        $("#mytable tr").show();
    else{
        $("#mytable tr[id=" + value + "]").show();
        $("#mytable tr[id][id!=" + value + "]").hide();
    }
  });

});

fiddle

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

Sharing and showcasing files directly from a local directory

Recently diving into NodeJS and web development, I've successfully used multer to upload a single file within my web application. The file gets uploaded to my "uploads" folder flawlessly, and now I'm planning on storing the file path in my databa ...

Can someone help me troubleshoot the issue with my submit button's onclick function?

I am currently working on a project where I have a content box enclosed in a div tag. Within this content box, there are paragraphs with unique IDs for individual styling rules. I have set margins, padding, and other styles accordingly. At the bottom of th ...

Utilizing React JS to neatly display Firebase data in a table

Before I post, I always make sure to do my due diligence by searching on Google, YouTube, forums, or trying to figure it out on my own. I even check questions similar to mine asked by other people, but unfortunately, I'm stuck. Currently, I am using ...

Tips on editing a file exclusively when a specific requirement is fulfilled

Looking for a way to implement a put method within an Express API that allows users to update a document conditionally? Consider this scenario: you have an Instance document with an attribute called executed, which is set to true if the instance has been e ...

Is there a way to switch the classList between various buttons using a single JavaScript function?

I'm currently developing a straightforward add to cart container that also has the ability to toggle between different product sizes. However, I am facing difficulties in achieving this functionality without having to create separate functions for ea ...

What is the correct way to outline the parameters for deactivating functions?

Request for Assistance! I am facing a challenge with multiple blocks in my WordPress website. Each block contains a checkbox, two select options, and an element that needs to be toggled based on the selected options in the dropdowns. The functionality to ...

Guide on crafting a side navigation menu that mimics the sleek functionality of mobile applications

Looking to develop a web app and mobile app hybrid, I started using bootstrap, jQuery, and Vuejs. Now, I aim to create a navigation menu that slides in from the left or right, similar to what we see in many mobile applications. To achieve this, I explored ...

Error: The variable "weather" is not defined while using React with the weatherbit API

I'm currently developing a React application that utilizes the Weatherbit API. However, I have encountered an issue with the weather object when calling my data array. Below is the code snippet where the problem occurs: import React from "react&q ...

Unable to integrate bower with gulp for automation

I am trying to get gulp to run the installation of all files listed in my bower.json. However, despite writing the code below, it is not working and I'm not seeing any errors. What could be causing this issue? var gulp = require("gulp"); var bower = ...

What causes the variable within the useEffect function to delay its value update?

const [inputValue, setInputValue] = useState(""); const previousInputValue = useRef(""); useEffect(() => { previousInputValue.current = inputValue; }, [inputValue]); return ( <> <input type="text" value={ ...

Performing a cross-domain JSON Get request with JQuery

Struggling with a simple JSON get request to an API on a domain that I don't have control over. Here's the code I'm using: $(document).ready(function () { $.ajax({ type: 'GET', url: 'http://pu ...

ng-disabled with function that activates on change

I am attempting to create a submit validation button that will only enable when all fields have been entered correctly. Due to the complexity of the validation process, I am unable to rely solely on formName.$invalid and need to write a custom function for ...

What is causing jQuery AJAX to fail in the second row?

I am currently updating a table with multiple columns. I have a specific column with a textarea that I want to update when the "#btnnVerify" button is clicked in the first row. The AJAX functionality works perfectly for the first row, but it fails to wor ...

How to import a dynamic typescript file in Next JS

As per the NextJs documentation, dynamic import can be used for JavaScript files like const DynamicComponent = dynamic(() => import('../components/hello')). Is it also advisable to use dynamic imports for .tsx files in a similar manner? ...

Navigating through each element of an array individually by using the onClick function in React

I'm currently working on a project that involves creating a button to cycle through different themes when pressed. The goal is for the button to display each theme in sequence and loop back to the beginning after reaching the last one. I've imple ...

Is there a way to prevent my token from being exposed when making an AJAX call?

When working on my HTML file, I encountered an issue with a Python Django URL integration where I need to pass a token to retrieve certain information. However, the problem is that my token is exposed when inspecting the page source in the HTML document. ...

Can you tell me which ng-class expression syntax belongs to AngularJS?

If you check out the AngularJS Noob Handbook, you'll find some code that simplifies class manipulation with a straightforward expression and binding: <a ng-click="flags.open=!flags.open">...<div ng-class="{active:flags.open}"> But what e ...

Could the issue at hand possibly stem from the fact that the router isn't fully operational? It appears that router.query

Having trouble retrieving the parameters from the URL using router.query. I've tried various approaches but keep getting an undefined result. It seems like I'm on the right track, though. Highlighted query param in yellow... https://i.stack.img ...

Guidelines for setting up Kendo notifications using an angularjs service

I have successfully defined the Kendo notification in my Angular service. However, when I try to use it with the line uiService.notify.error("You missed some required fields.");, I am getting an error that says "Cannot read property 'show' of nul ...

Dealing with a unique key error in a loop while using React and Google

I've implemented a react-google-maps component that successfully retrieves data from various locations. However, I'm encountering an error message in the console: Warning: Each child in a list should have a unique "key" prop. I made s ...