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

Efficiently transferring input to a Typescript file

Is there a better way to capture user input in Angular and pass it to TypeScript? <form > <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" /> </form> The current method involves creating a ...

Swap out the HTML button element for text once the form is submitted

On the main page, I have a button that opens a modal when clicked. Inside the modal, there is a form with a submit button that closes the modal and returns to the main page. After closing the modal, I want to change the HTML button on the main page to plai ...

Here's a unique rewritten version: "Achieving a looping carousel with autoplay in Angular 2+ using with

Could someone provide recommendations for an image carousel that is compatible with angular 8? I would also like to know how to customize the images inside the carousel specifically for small devices. Thank you in advance! ...

Is it possible to specify the same attribute multiple times within an HTML5 element?

After reviewing the HTML5 specification (W3C Recommendation 28 October 2014), I am unable to locate any specific information on whether an element can have the same attribute specified multiple times. For instance, the attribute style sometimes has a lengt ...

Leveraging angular.extend() with controllers and function overrides

Currently, I am working with Angular 1.4.8 and attempting to expand a controller. The original controller and the expanding controller are quite similar, but there is a specific function that I aim to replace in the extending controller. angular.module(&a ...

Unable to impose a restriction on the number input field limit

My input field has a type of "number" with the min and max attributes applied to limit user input. However, I am facing an issue where users can still enter values beyond the set limit. How can I prevent users from entering values above the specified lim ...

Encountering a problem when trying to use event.target.value in an Angular TypeScript application

Here is the code from my app.component.html : <h1>Password Generator</h1> <div> <label>Length</label> </div> <input (input)="onChangeLength($event.target.value)"/> <div> <div> <input ...

jquery sequential fade effect

I am trying to make each div fade in one by one. Visit this link for reference <div id="w"> <div class="one"></div> <div class="two"></div> <div class="three"></div> </div> $(function() { $(&a ...

When the document is fully loaded on a page that has been dynamically loaded

Currently utilizing the following: $("#someDiv").load("ajax.html") The contents of "ajax.html" include a document.ready call: <script>$(function() { alert('works') })</script> I'm interested to know exactly when this callbac ...

jquery: conditions fail to execute

Looking at the code snippet provided, it appears quite straightforward. The intention is to display an alert labeled "Trigger 2" if the variable "ret" returns a value of "fail". However, there seems to be a glitch with the IF statement causing it to trigge ...

Ways to specify the styles for tr, td, and label elements within a material table

Hey there! Currently, I'm working with material table in react. I came across this page: https://material-table.com/#/docs/features/styling, where it mentions that we can use cellStyle, headerStyle. But what if I want to add more detailed styles to e ...

Looking to minimize the amount of HTML code in Angularjs by utilizing ng-repeat

Working with some HTML <tr class="matrix_row" ng-repeat="process in matrixCtrl.processes | filter : { park: parentIndex } track by $index"> <td class="properties" ng-click="dashboardCtrl.currParam=0; dashboardCtrl.currentProcess=process"> ...

What are the steps to achieve the desired PrimeFaces theme appearance for selectOneMenu?

Need help with a JSF Primefaces project using the omega theme. The selectOneMenu dropdowns are not displaying correctly (missing line). Current look: https://i.stack.imgur.com/vF4ms.png Expected look: https://i.stack.imgur.com/hXsIB.png Any suggestion ...

The HTML table printout is missing cells in the first column

Encountered a strange issue with Internet Explorer and Chrome involving a basic HTML table. The table has no layout CSS, 2 columns, no styles, and its width is set to 100%. When attempting to print the table in these browsers, the first cell on the second ...

Ways to emphasize the contrast between two texts using CSS

One method to highlight specific parts of text using CSS can be found in this script: span.highlight { background-color: #B4D5FF; } However, what if we want to highlight the differences between two strings? Take for example these two strings: this ...

floating downward inside the container

Check out my website at . Everything looks great in Firefox, but when I view it in IE, the "top" button that should be floated inside the h2 titled "Unit 301: Pre-production skills" is floating to the right and getting pushed outside of the heading. Any i ...

I am experiencing an issue with my date filter where it does not display any results when I choose the same date for the start and end dates. Can anyone help me troub

Having an issue with my custom filter pipe in Angular. When I select the same dates in the start and end date, it doesn't display the result even though the record exists for that date. I've noticed that I have to enter a date 1 day before or ea ...

CSS Issue: Hovering Over Link Causes Text to Shift in Internet Explorer

Encountering a problem with CSS and IE, specifically in Internet Explorer 9. When hovering over certain links, the text shifts down which does not occur when using Firefox. You can see an example of this issue at: http://www.debtdispatch.com/list_item_err ...

Upon its second use, Ajax is loaded with cached data

Imagine a table with multiple rows, each row containing a SHOW button that reveals hidden content when clicked. The hidden div (with the classname "Content") loads the content of a second page using ajax and the id of the corresponding table row. However, ...

Display the div only when the time variable reaches zero

I want to display a div when the difference between the time imported from the database and the current time is 0. How can I achieve this? Here is the code snippet: while ($row = mysqli_fetch_array($result)) { echo "<div class='alert' id= ...