Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the page loads, but once a user selects an option from the dropdown, only that selected value will remain visible while others disappear.

This is my current JavaScript implementation:

 function select_mem() {
        if ($("select[name='status-type']").val() == "all") {

            $('.num-good').show();
            $('.num-not').show();
            $('.num-not-working').show();
            $('.num-bad').show();
            $('.num-blue').show();

        }
  if ($("select[name='status-type']").val() == "good") {

            $('.num-good').show();
            $('.num-not').hide();
            $('.num-not-working').hide();
            $('.num-bad').hide();
            $('.num-blue').hide();

        }
 if ($("select[name='status-type']").val() == "bad") {

            $('.num-good').hide();
            $('.num-not').hide();
            $('.num-not-working').hide();
            $('.num-bad').show();
            $('.num-blue').hie();

        }
  if ($("select[name='status-type']").val() == "not-working") {

            $('.num-good').hide();
            $('.num-not').hide();
            $('.num-not-working').show();
            $('.num-bad').hide();
            $('.num-blue').hide();

        }
 if ($("select[name='status-type']").val() == "not") {

            $('.num-good').hide();
            $('.num-not').show();
            $('.num-not-working').hide();
            $('.num-bad').hide();
            $('.num-blue').hide();

        }
 if ($("select[name='status-type']").val() == "blue") {

            $('.num-good').hide();
            $('.num-not').hide();
            $('.num-not-working').hide();
            $('.num-bad').hide();
            $('.num-blue').show();

        }

    }

This is how I have structured the HTML:

    <section class="filter">

        <p>Filter your search: <select id ="options" name="status-type" onChange="select_num()">
            <option id="all" value="all">All Numbers</option>
            <option id="good" value="good">Good Numbers</option>
            <option id="bad" value="bad">Bad Numbers</option>
            <option id="not-working" value="not-working">Not Working Numbers</option>
            <option id="not" value="not">Non Numbers</option>

        </select></p> 
    </section>

    <!-- Valid Numbers -->
    <table>
<thead>
<tr>
    <th>Number</th>
    <th>Status</th>

</tr>
</thead>
<tbody>

// Table rows with corresponding classes for different statuses

</tbody>

The code can be accessed on jsFiddle via this link: http://jsfiddle.net/hodhLyw1/1/

I'm exploring the use of jQuery for this functionality, but would appreciate any suggestions for achieving the same outcome using pure JavaScript. Thank you in advance for any guidance provided!

Answer №1

If you find yourself writing repetitive code, you can simplify it like this:

let $rows = $('tbody tr'); // store all table rows in a variable

$("select[name='status-type']").change(function(){
    let val = $(this).val();  // get the current value
    if( val == 'all'){
       $rows.show(); 
    }else{
       // hide all rows then show ones that match the selected filter
       $rows.hide().filter('.num-' + val).show();
    }
});

Check out the DEMO

Answer №2

If you want to update a CSS selector, consider changing $("select[name='status-type']") to

document.querySelector("select[name='status-type']")
. Subsequently, replace .val() with .value in vanilla JavaScript.

To show or hide elements, you can utilize myElement.hidden = false to display an element or myElement.hidden = true to hide it. Alternatively, adding a class using

myElement.classList.add('myclass')
(similar to jQuery's myElement.addClass()) and removing it with classList.remove() are also effective methods.

For further insights into vanilla DOM manipulation techniques, check out the resources available on the Mozilla Developer Network.

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

Retrieve the HTML data and save it as page.html, displayed in a VueJS preview

After developing an innovative VueJS-based application for managing front-end content, I am now eager to enhance it with a 'download' button feature. This new functionality will allow users to easily download the previewed and edited content in H ...

How to Align Video Alongside Image in HTML without Using CSS

Is there a way to place a video on the left and an image on the right of the same line in HTML without relying on CSS? ...

Creating a form with an input field and an image side by side in HTML

I've been attempting to display an HTML input element and an SVG image on the same line without success. I've tried various solutions from stackoverflow, but none seem to work for me. Here's my current HTML code: <div id = "inline_eleme ...

What method can I use in pure Javascript to identify which day the week begins on, either Monday or Sunday, based on the

Can someone help me determine the start day of the week in local time using only Javascript? The start day could be Monday, Sunday, Saturday, or Friday. I came across this helpful resource on Stack Overflow: <firstDay day="mon" territories="001 AD AI ...

Ensuring consistency of variables across multiple tabs using Vue.js

In my vuejs front-end, a menu is displayed only if the user is logged in. When I log out, the variable isLogged is updated to false, causing the menu to hide. If I have multiple tabs open with the frontend (all already logged in) and I logout from one tab ...

Comparing global variables in ng-switch: Best practices

I'm currently utilizing the AngularJS $rootScope object to expose some global constants that should be accessible to both controllers and views: var app = angular.module('myApp', []); app.run(function ($rootScope) { $rootScope.myConsta ...

Tips on placing an li element into a designated DIV

Just starting out with jquery and working on a slider project. Here's what I have so far: <ul> <li> <img src="image.jpg"><p>description of the current image</p></li> <li> <img src="image.jpg"> ...

Exploring the methods for retrieving and setting values with app.set() and app.get()

As I am granting access to pages using tools like connect-roles and loopback, a question arises regarding how I can retrieve the customer's role, read the session, and manage routes through connect-roles. For instance, when a client logs in, I retrie ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

How to Incorporate LessCSS into the Blueprint Framework?

Can LessCSS be integrated with Blueprint framework? What are the prerequisites for starting? ...

What could be the reason for the function providing the value of just the initial input?

Why am I only getting "White" when I click on the colors? I can't seem to get any other values to appear on the screen. I'm confused about what mistake I might be making here. var x = document.getElementById("mySelect").value; function myFunc ...

Dynamic AJAX Dependent Dropdown Menu

Can you help me create a dynamic input form? I need assistance in creating an input form with a dynamic dropdown list, similar to the screenshot provided below: https://i.stack.imgur.com/rFSqV.png What is my current script setup? The script I have is d ...

Steps on how to trigger an onmouseover event for entire blocks of text:

I'm currently in search of an onmouseover code that seems to be elusive on the vast internet. A CSS box format has been successfully created: .box { float: left; width: 740px; height: 300px; margin-left: 10px; margin-top: 10px; padding: 5px; border: ...

The CSS Accordion seems to be the culprit behind the missing margin or border at the top of my page

Although everything on the page is functioning as desired, there seems to be a missing margin or border that is not causing much trouble. If there is a simple solution or an easy way to identify why this is happening, it would be greatly appreciated. Take ...

Maintain fullcalendar event filtering across multiple renderings

I currently have a fullcalendar that initially displays all events. I am using a select dropdown to filter the events, which works well. However, when the calendar re-renders after moving to the next month, it shows all events again. Here is my calendar in ...

Strategies for Locating XPath Using Text Content within Table Cells (td / tr)

Need help with searching for specific text within a large HTML table of emails and selecting a button within the element? You can easily find the table body via XPATH by using: //*[@id="reportList"]/tbody Within this table, there are multiple rows (tr). ...

How can I designate the file name when using Ajax to export in Excel formatting?

Can you help me with the code to set a specific filename for downloading an Excel file? if(comp_id != "Select Company") { $.ajax({ url: 'includes/export.php', data: { action: 'compreport', 'comp':comp_i ...

Use Puppeteer and Node.js to repeatedly click a button until it is no longer present, then initiate the next step

Imagine a dynamic web page filled with rows of constantly updated data. The number of rows on the page remains fixed, meaning old rows are replaced and not stored anywhere. To navigate through this page, you need to click on a "load more" button that app ...

I am encountering TypeError issues while attempting to mock/test Vuex store modules

I'm currently in the process of learning how to effectively test components and JavaScript code, but I have hit a roadblock with Vuex modules. Below is the code snippet for the test: import { shallowMount } from '@vue/test-utils' import Wor ...

Every time I attempt to execute route.js in my API folder, I encounter a persistent 404 error

Project Structure: https://i.stack.imgur.com/qMF6T.png While working on my project, I encountered an issue with a component that is supposed to call an API function. However, it seems like the file is not being found. I have double-checked the directory ...