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

AngularJS: Optimizing Image Loading for the Initial Page Load in AngularJS

Currently, I am working with a JSON object that contains image URLs which I am displaying using ng-repeat. However, I have encountered an issue where the images flicker when the page loads for the first time. I am looking to implement a preloader (CSS spin ...

Updating a dataview inside a Panel in extjs 3.4

I am facing an issue with my extjs Panel component that includes a dataview item. Initially, it works perfectly fine in displaying images from a store. However, upon reloading the imgStore with new image URLs (triggered by a user search for a different cit ...

Instructions on utilizing module.exports to export an async function

I am facing an issue with returning the result of an async function to the route I am calling. How can I resolve this successfully? My goal is to export a token from file token_generator.js and display it on route ('/') using Express. The functi ...

Secure JSON data by transmitting it safely to the front end within a Node.js environment

Currently, I am in the process of building an e-commerce application using NodeJs, Express, and MongoDB. The challenge I am facing is deciding how to securely pass JSON objects from the back end to the front end without compromising data security. Initiall ...

Tips for updating Angular HTML with data received from Socket.IO

I am currently working on a socket program that is listening and providing log data. The socket is sending the correct data as I can see it in the console. Below is a snippet of my code: export class RoboLogComponent implements OnInit { dataToShow:any @V ...

I am unable to access my JavaScript class in Laravel Mix

Within my Laravel project, I have developed a custom form validation class. However, after running npm run dev, I am unable to access this class. Files: small-form-validation.js class SmallFormValidator { errMsgs = { required: 'This fiel ...

Can I store a large batch of images in one location and retrieve them using a REST API?

So here's the situation: I currently have a large collection of images saved on my Mac. I'm working on a landing page that resembles an ecommerce deal site. Manually inputting the src url for each of the thousand pictures would be incredibly tim ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...

The function dataTable is not recognized as a valid command

I am encountering an issue while attempting to utilize the datatables plugin. Whenever I call the function dataTable(), I receive an error. Here is a snippet of my code: @Scripts.Render("~/Scripts/DataTables-1.9.4/media/js/jquery.js") @Scripts.Render("~/S ...

Angular.js - index template fails to execute controller, but other templates work flawlessly

I am facing a strange issue with my Angular application that uses ngRoute. I have set up different controllers for each template in the routes.js file: routes.js: angular.module('PokeApp', ['ngRoute']) .config(function($routeProvide ...

What methods can I use to sort content by its rating?

I am embarking on my inaugural project and attempting to construct a product filtering system. So far, I have successfully implemented search and category filters; however, configuring the rating filter has proven to be challenging. Here is an excerpt of ...

Does this information operate on Vue or Node?

I have recently started learning programming and currently working on an HTML project for school. My professor mentioned that we should only use Node.js for this project. However, I am concerned that the function I used below might be Vue instead of Node ...

Display WordPress die errors as an alert message

During my current project, I have encountered a function that is working well so far except for the issue of displaying an error message in an alert popup when the function fails. This particular function involves Ajax scripting. Below is the code snippet ...

When I try to move my object, it seems to have a mind of its own and flies off the canvas instead of staying where

I am in the process of developing a simple game for a class project. Currently, I am working on ensuring that my rectangle stays within the boundaries of the canvas as I move it using a bounce function. However, I am facing difficulties as the rectangle ...

Retrieve the values from the second dropdown list based on the choices made in the first dropdown menu within a React application

Hi there. I am attempting to create a cascading dropdown menu using the data from api. For example, in the first dropdown, I have the following options: 1. Fruits 2. Roots 3. Flowers If I select Fruits, then Orange, Apple, and Strawberry should appear. ...

The absence of a key is causing an issue - deletion cannot be completed

I need assistance with removing a question after it has been answered, but I am encountering an error message stating that my key is undefined. Error: DELETE http://api/Remove/undefined 400 (Bad Request) state={ qBank:[{id=1,question:'dd',answers ...

The express gateway is unable to transfer multipart/formdata

I've implemented express gateway as my main service gateway. One of the services I have needs to update an image, and when I try to handle files independently using multer it works fine. However, once this service is routed through express gateway, th ...

Organize the HTML output generated by a PHP array

There must be a simple solution to this, but for some reason, it's escaping me right now. I've created custom HTML/CSS/JS for a slider that fetches its content from an array structured like this: $slides = [ [ 'img' = ...

Using Node.js, Express, and Socket.IO to establish real-time communication between two static client pages

I'm in the process of creating a remote control for a gallery using nodejs, express, and socket.io. Here's the project structure: /index.js /public/screen.html /screen.js /remote.html /remote.js The goal is to display a gallery of ima ...

Submitting a form triggers the process of uploading images to Firebase

I have been working on a small web app similar to a blog using AngularJs and Firebase. Initially, I successfully implemented the addPost controller. However, when I tried to incorporate an input file within the form to upload images to Firebase upon form s ...