Filtering a table based on user selection: specifying column, condition, and value using JavaScript

I am new to JavaScript and looking to implement real-time filtering on a table based on user input. My project utilizes Django and PostgreSQL for storing the table data.

template

<form action="" method="get" class="inline">

        <select name="column" class="form-control">
            <option value="" selected disabled>Select field</option>
            <option value="title">Title</option>
            <option value="quantity">Quantity</option>
            <option value="distance">Distance</option>
        </select>

        <label for="table">Condition</label>

        <select name="condition" class="form-control">
            <option value="" selected disabled>Select condition</option>
            <option value="greater">Greater than</option>
            <option value="contains">Contains</option>
            <option value="lower">Lower than</option>
            <option value="equals">Equals to</option>
        </select>

        <input class="form-control" type="text" placeholder="Search term" id="search-text" onkeyup="tableFilter()">

        <button type="submit">Apply Filter</button>
</form>

https://i.sstatic.net/a0vMt.png

Thank you in advance for any assistance :)

Would this approach be effective?

function tableFilter() {
    var input = document.getElementById("search-text");
    var filter = input.value.toUpperCase();
    var table = document.getElementById("myTable");
    var tr = table.getElementsByTagName("tr");

    for (var i = 0; i < tr.length; i++) {
        var tds = tr[i].getElementsByTagName('td');
        var firstCol = tds[0].textContent.toUpperCase();
        var secondCol = tds[1].textContent.toUpperCase();
        
        if (firstCol.indexOf(filter) > -1 || secondCol.indexOf(filter) > -1) {
            tr[i].style.display = "";
        } else {
            tr[i].style.display = "none";
        }      
    }
}

Answer №1

Have you experimented with the array.filter() method?

const data = [
  { title: 'spray', quantity: 40, distance: 300 },
  { title: 'pray', quantity: 10, distance: 150 },
  { title: 'grey', quantity: 23, distance: 100 }
];
const result = data.filter(each => each[quantity] < 23 );
console.log(result);
// expected output: Array [{ title: 'pray', quantity: 10, distance: 150 }]

You also have the option to utilize eval and dynamically modify the condition.

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

Implementing change event to activate select dropdown with jQuery

Is there a way to modify the code so that select2 and select3 are disabled by default, but become enabled only when an option is selected in the previous select dropdown (excluding the placeholder "Select your option")? In addition, I want the first place ...

Using jQuery to verify the existence of a lengthy object

Is it possible to achieve this functionality using jQuery or other libraries? Dojo has this feature, but what about the others? $.ifObject(foo.bar.baz.qux[0]) if (foo && foo.bar && foo.bar.baz && foo.bar.baz.qux[0]) With an unkno ...

Ingress-nginx rewriting destination target

I have set up an nginx ingress for my front-end built in vuejs. apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: vuejs-ingress namespace: default annotations: cert-manager.io/cluster-issuer: letsencrypt-prod nginx.ingress.kubern ...

What is the best way to apply a class to a jQuery element only if a specific condition is met, and then remove it if the condition is no longer

Is there a more concise method to accomplish the same task? const selectAllCheckbox = $("input.select_all"); const isChecked = selectAllCheckbox.prop("checked"); isChecked ? selectAllCheckbox.parent().addClass("selected") : selectAllCheckbox.parent().r ...

Moving a window in Pyqt5 using QtWebChannel

My goal is to enable the mousePressEvent and mouseMoveEvent events in order to move my app window using QtWebChannel. To achieve this, I am utilizing self.setWindowFlags(QtCore.Qt.FramelessWindowHint) to eliminate the default window flag and create a cust ...

Switching the visibility of multiple textareas from block to none

I am currently exploring ways to make one text area disappear while another one appears in its place. With limited knowledge of Javascript and just starting my journey into HTML and CSS, I am reaching out to the forum for assistance or guidance on the rig ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

Oops! The Route.get() function in Node.js is throwing an error because it's expecting a callback function, but it received

Currently, I am learning how to create a web music admin panel where users can upload MP3 files. However, I have encountered the following errors: Error: Route.get() requires a callback function but received an [object Undefined] at Route. [as get] (C:&bso ...

I have noticed that the baseline of a Span element has shifted after updating my Chrome browser to a version that begins with

Once I updated to chrome Version 108.0.5359.94 (Official Build) (64-bit) from 107.0.5304.87 (Official Build) (64-bit), the behavior of the span element changed drastically. It shifted its baseline when multiple spans were stacked on top of each other. Exp ...

Adjusting Text Size Depending on Width

I recently used an online converter to transform a PDF into HTML. Check out the result here: http://www.example.com/pdf-to-html-converted-file The conversion did a decent job, but I'm wondering if it's feasible to have the content scale to 100% ...

What is the process for assigning a regular expression to an object?

As I work on editing a configuration file, I'm encountering some issues where things aren't quite functioning as expected. Below is the code snippet I am working with: config.module.rules.unshift( { test: "/ckeditor5-[^/\\ ...

Error encountered in Pokemon API: Trying to access property '0' of undefined

My current challenge involves accessing the abilities of my Pokemon, but I keep encountering a recurring error. In my project development using React hooks, I fetched data from the Pokemon API and stored it in setWildPokemon. Utilizing wildPokemon.name suc ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...

Issue encountered in Angular 4 due to XSS script in URL causing "Cannot match any routes" error

I've been working on a project in Angular 4 and encountered an issue while setting up routes for a feature module. The error message I'm receiving is Error: Cannot match any routes. Below is the code snippet of the routes I've defined: con ...

A guide to examining pixels in Three.js

I have a query about comparing two textures at a pixel level in three.js. I am unsure of how to achieve this as the documentation for Three.js does not provide clear answers, with some classes remaining undocumented. In summary, I am looking to determine ...

Ways to ensure the CSS style remains active even after clicking the button

Is there a way to make the effect appear only when the button is clicked, then disappear after it's released? I've seen examples using addEventListener and directly changing the style with btn.style.color="" (reference) or using btnEl.c ...

Is there a way to initiate a callback function once all the contents of an UpdatePanel have been fully loaded?

Looking for a solution with an ASP.NET UpdatePanel that contains multiple images. I am trying to trigger some javascript code after the UpdatePanel is refreshed, but only after all images have finished loading. I attempted using add_endRequest as a callb ...

Tips for deselecting a selected item in Vuetify's list item group

I am working on a vuetify 2.0 view-list setup where selecting an item populates a form for editing, following the standard list-detail design pattern. The selected item is highlighted in the list, but I want to clear the form if the same item is selected a ...

Assistance required for activating an unidentified function or plugin within a Chrome extension

I am currently working on a project involving a chrome extension designed to automate tasks on a specific website. My main focus right now is trying to trigger the click event of a link that has an event handler set up through an anonymous function as show ...

Guide on hiding a div element when clicked outside of it?

How can I create a dropdown feature in Khan Academy where it disappears when clicked outside but stays visible when clicked inside, using JavaScript/CSS/HTML? The current implementation closes the dropdown even on internal clicks. The code includes an even ...