Hide specific elements based on chosen options in different classes using the displayNone property

I need help with a jQuery script that can hide certain elements based on the selected option value from a drop-down menu. I want to be able to read the text content of the selected option value and then hide specific div classes accordingly:

<div class="filter_options">
    <input id="search_query" type="hidden" value="Texts" />
    <fieldset class="filterType">
        <label>Filter By Type</label><select id="search_filter_type">
            <option value="">All</option>
            <option value="Cat">Cat</option>
            <option value="Dog">Dog</option>
        </select>
    </fieldset>
</div>

The goal is to hide the div classes with the "pg_list" class that do not contain the selected value from the drop-down menu.

<div class="pg_list">
    <p>This text contains a Dog</p>
</div>

<div class="pg_list">
    <p>This text contains a Cat</p>
</div>

<div class="pg_list">
    <p>This text contains a Rabbit</p>
</div>

For example, if the user selects "Cat" from the drop-down menu, it should hide the div containing "Dog" or "Rabbit", leaving only the one containing "Cat".

I have already prepared the necessary CSS:

.displayNone{
    display: none;
}

Here is my existing jQuery code, which currently works for an input text field but needs modification to work with a selected drop-down value:

$('input').on('keypress keyup', function(){
var value = $(this).val().toLowerCase();
if (value != '') {

  $('.pg_list').each(function () {
    if ($(this).text().toLowerCase().indexOf(value) > -1) {
      $(this).removeClass('displayNone');  
    } else {
      $(this).addClass('displayNone');
    }
  });
} else {
  $('.pg_list').removeClass('displayNone');
}

Thank you for your assistance!

Answer №1

To begin, you must make sure to choose the correct element, which in this case is the dropdown box identified by the code: $('#search_filter_type'). Next, you want this action to take place when there is a change in the value of the dropdown box:

$('#search_filter_type').on('change', ...

$('#search_filter_type').on('change', function() {
  var val = $(this).find('option:selected').text().toLowerCase();
  if (val != "all") {

    $('.pg_list').each(function() {
      if ($(this).text().toLowerCase().indexOf(val) > -1) {
        $(this).removeClass('displayNone');
      } else {
        $(this).addClass('displayNone');
      }
    });
  } else {
    $('.pg_list').removeClass('displayNone');
  }
});
.displayNone {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filter_options">
  <input id="search_query" type="hidden" value="Texts" />
  <fieldset class="filterType">

    <label>Filter By Type</label>
    <select id="search_filter_type">

      <option value="">All</option>
      <option value="Cats">Cat Pictures</option>
      <option value="Dogs">Dog Pictures</option>
    </select>
  </fieldset>

</div>
<div class="pg_list">
  <p>In this text, you will find Dog Pictures</p>
</div>

<div class="pg_list">
  <p>This text includes images of Cat Pictures</p>
</div>

<div class="pg_list">
  <p>There are references to a Rabbit in this text</p>
</div>

Answer №2

When using jQuery to retrieve the value of a <select>, the process is similar to that of an <input>:

$('#my-select').val(); // replace 'my-select' with your select element

To trigger this action when the selection changes, you can utilize a change event:

$('#my-select').on('change', function() {
    var value = $(this).val().toLowerCase();
    // continue with your code here
});

If you wish to access the text of the selected option instead, you can use the following approach:

$('#my-select').on('change', function() {
    var value = $(this).find('option:selected').text();
    // continue with your code here
});

An enhancement for your design could involve adding a specific class to each <div> element, corresponding to the option value. By doing so, you can easily manipulate their visibility without extensive looping by leveraging the not() method.

$('select').on('change', function () {
  var value = $(this).val();
  $('#divs').children() // all children within the designated parent
    .removeClass('displayNone') // remove 'displayNone' class from all elements
    .not('.' + value) // exclude the element we want visible
    .addClass('displayNone'); // add 'displayNone' class to remaining elements
});
.displayNone {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="">-- Select --</option>
  <option value="dog">Dog</option>
  <option value="cat">Cat</option>
  <option value="rabbit">Rabbit</option>
</select>
<div id="divs">
  <div class="cat">Cat</div>
  <div class="dog">Dog</div>
  <div class="rabbit">Rabbit</div>
</div>

This approach offers more flexibility as it does not rely solely on matching text and eliminates the need for comparing texts through loops.

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

I'm struggling to interpret the reply received from $.ajax

Looking to make adjustments to my existing code in order to add comments for images that are fetched using $.ajax and returned as html. The plan is to retrieve the comments as a JSON object, and then parse the previously obtained HTML to insert the commen ...

What is the best way to verify a password's strength with Joi so that it includes 2 numbers, 2 special characters, 2 uppercase letters, and 2 lowercase letters?

Is there a way to achieve this using Joi? For instance: Joi.string() .required() .min(8) .max(16) .pattern(/(?=(?:.*[a-z]){2,16}).+/) .pattern(/(?=(?:.*[A-Z]){2,16}).+/) .pattern(/(?=(?:.*[0-9]){2,16}).+/) .pa ...

I must retrieve cookies from the GET call API within the route.js file

I've developed a website using Next.js 13 with a route called /api/users/me. In this route, I need to access the cookies to extract the token. While calling the API from the browser gives me the desired result, trying to call it from the frontend page ...

Unraveling the intricacies of Wordpress, PHP, and HTML

What is the purpose of the post, ID, and other elements within the article tag? I expected the post_class to be defined in my CSS, but I cannot locate it. If I remove the entire code block from the <article>, my website layout breaks. However, remov ...

What are some ways I can optimize my Bootstrap CSS code to enhance responsiveness across different page widths?

After creating this fiddle, I noticed that my webpage layout with two texts stacked on top of each other looks great on wide screens. However, when the screen size is reduced or viewed on a mobile device, the layout gets all messed up. Take a look at this ...

What could be causing my header component to rerender even when there are no new props being received?

https://codesandbox.io/s/crimson-field-83hx6 In my project, I have a Header component that simply displays a fixed text and includes a console.log statement: const Header = props => { console.log("header render"); return ( <header> ...

Adding an attribute to the last item of an Angular / NGX Bootstrap component

I am working with a dynamic list that utilizes NGX Bootstrap Dropdowns to showcase 4 sets of dropdown lists. However, the Dropdowns in the final list are getting obscured off-page. Thankfully, NGX Bootstrap offers a solution in the form of a dropUp option ...

Building a linked list in Javascript with pointers

After implementing a linked list in two different ways using Javascript, I found myself in a state of confusion about the inner workings of the code. Trying to mentally visualize the creation process and the memory addresses being referenced proved to be ...

Tips for enabling the `ignoreUndefinedProperties` feature in Node.js

I'm currently in the process of creating a REST api for my Node.js and Express application. However, I keep encountering an error stating that properties are undefined whenever I attempt to send a request. How can I go about enabling 'ignoreundef ...

PHP script failing to execute if/else statement during AJAX request

I am currently developing a website that heavily relies on Ajax, and I have chosen to use codeigniter for its construction. On the site, there is a form with the post method, and this form is submitted using an Ajax request that calls a function containi ...

Tips for limiting a website to load exclusively within an iframe

I am managing two different websites: https://exampleiframe.com (a third-party website), https://example.com (my own website) My goal is to limit the loading of https://example.com so that it only opens within an iframe on https://exampleiframe.com To a ...

Display a specific section of an image as the background in a div, with the image scaled and positioned perfectly

Utilizing a 1900 x 1080 image within a div as the background <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <style> html,body { height:100%; } #imageHolder{ ...

The componentWillUnmount method is not being called

I'm currently working on a Backbone application and I'm in the process of integrating React components. The React component is being mounted using the following code: ReactDOM.render( <WrappedComponent />, node ); where "node" represents ...

Learn the secrets of displaying a pop-up alert message seamlessly without interrupting the page's rendering process. Additionally, discover how to effortlessly refresh a chart every

I need to display a pop-up if the value is less than 3. I have tried using the alert function, but it causes the page to not render. How can I show the pop-up without blocking the page and refresh the chart every 30 seconds? <script> ...

Challenges encountered when attempting to download a file using jQuery's GET method

I am working with an API Server that responds to requests in the following format: http://localhost:8080/slim3/public/api/v1/files/Test1.jpg http://localhost:8080/slim3/public/api/v1/files/Test2.txt ... When I enter such a URL into my browser, I receive ...

Tips for retrieving keycodes/key/which values for DOMSubtreeModified Event

Searching for the keycode pertaining to the DOMSubtreeModified event, but encountering undefined results <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> $(document).ready(function(){ ...

Incorporate an onclick event to the elements within the array

I'm currently working on iterating over an array and adding an onclick event to each element. My goal is to be able to click on each div and have them log their values in the console. However, I am facing a challenge in applying the onclick event to e ...

Tips for sending JSON-formatted data from a route to jQuery

Currently, I am facing a challenge with passing a JSON file retrieved from an API to jQuery. The goal is to implement an infinite scroll functionality using jQuery before displaying it in an EJS file. The issue arises when `res.json(data)` is utilized; ins ...

Sophisticated Sidebar Design using Bootstrap 5

Looking to design a responsive sidebar for navigation on my page, with selected and hover properties. Visualizing the selected option to appear like this: Selected (active) option in sidebar The goal is to have the image cover the left side of the backgr ...

Achieving decimal increments in Bootstrap Slider on a View Page

How can I create a Bootstrap slider with values incrementing by 0.01 and only allow users to select values between 4 and 12? Moving the slider should increase values in increments of 0.01. Razor/HTML <input id="inputRateOfInterest" type="text" /> ...