Jquery is unable to showcase search results based on the 'data-name' attribute

Building a search feature below that filters results based on the data-name attribute. For instance, if the user types "XL," all div elements with data-name as "XL" will be displayed. I am able to see all results but the other buttons aren’t showing any outcomes.

The issue lies in the functionality of the buttons while the input field works properly.

Visit this link for a working example

Below is the code snippet:

$(document).ready(function(){
  $("#searchInput").on("keyup", function(){
    var value = $(this).val().toLowerCase();
    $("#searchFilterDiv div.SearchItem").filter(function(){
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });

var btns = $('.filter-button').click(function(){
  if($(this).data('name') == 'all'){
    $('#searchFilterDiv div.SearchItem').fadeIn(450);
  }else{
    var otherData = $(this).data('name');
    $('#searchFilterDiv div.SearchItem.search-results-box-item').not(otherData).hide();
  }
btns.removeClass('active');
  $(this).addClass('active');
})

});
.service-boxes-centered li {
    min-width: 100px;
    padding-top: .8em;
    padding-bottom: .8em;
    padding-left: 1em;
    padding-right: 1em;
    font-size: .9em;
    margin: .3em;
    color: #4b4b4b;
    text-decoration: none;
    flex-grow: 1;
    text-align: center;
}

.service-box-item {
    border: 1px solid #979797;
    font-size: .8em;
    font-weight: 500;
    cursor: pointer;
    display: inline-block;
    text-align: center;
}

.search-results-box-item {
    border: 1px solid lightgrey;
    margin-bottom: 2em;
    padding: 20px;
    font-size: .8em;
    line-height: 1.3em;
    text-align: left;
    cursor: pointer;
  }

.service-box-item.filter-button.active{
  border: red 1px solid !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="container form-container">
  <div class="row search-form-item">

    <div class="col-md-12 searchtext-input">
  <h3>search by size: </h3>
  <label for="searchInput" class="sr-only">Search field</label>
      <input class="form-control" id="searchInput" type="text">
  <div class="row service-boxes-centered">
  <ul>
          <li class=" service-box-item filter-button active" data-name="all">All</li>
  <li class=" service-box-item filter-button" data-name="XS">XS</li>
  <li class=" service-box-item filter-button" data-name="S">S</li>
  <li class=" service-box-item filter-button" data-name="M">M</li>
  <li class=" service-box-item filter-button" data-name="L">L</li>
  <li class=" service-box-item filter-button" data-name="XL">XL</li>
          <li class=" service-box-item filter-button" data-name="2XL">2XL</li>
          <li class=" service-box-item filter-button" data-name="3XL">3XL</li>
        </ul>
  </div>
    </div>

  </div>

  <div class="container" id="searchFilterDiv">
    <div class="row">

        <div class="SearchItem search-results-box-item" style="padding-bottom: 2em; display: block;" data-name="M, XL, S, 2XL">
          <h3>flipside</h3>
            <p>Vivamus viverra libero sed mi vehicula euismod. Nullam mauris dolor, hendrerit non lorem nec, vehicula dapibus nisl. In posuere est lectus, consequat tempus velit laoreet ut.</p>
            <p>M</p>
            <p>XL</p>
            <p>S</p>
            <p>2XL</p>
  <br>

    </div>
    
     <div class="SearchItem search-results-box-item" style="padding-bottom: 2em; display: block;" data-name="M, S">
          <h3>frontside</h3>
            <p>Vivamus viverra libero sed mi vehicula euismod. Nullam mauris dolor, hendrerit non lorem nec, vehicula dapibus nisl. In posuere est lectus, consequat tempus velit laoreet ut.</p>
            <p>M</p>
            <p>S</p>
            
  <br>

    </div>
    
     <div class="SearchItem search-results-box-item" style="padding-bottom: 2em; display: block;" data-name="S, XS">
          <h3>leftside</h3>
            <p>Vivamus viverra libero sed mi vehicula euismod. Nullam mauris dolor, hendrerit non lorem nec, vehicula dapibus nisl. In posuere est lectus, consequat tempus velit laoreet ut.</p>
            <p>S</p>
            <p>XS</p>
            
  <br>

    </div>


      
    </div>
  </div>

 

Answer №1

One useful approach is to loop through all of your data and search for the specific data-name you are interested in.

 var buttons = $('.filter-button').click(function(){
    if($(this).data('name') == 'all'){
        $('#searchFilterDiv div.SearchItem').fadeIn(450);
    }else{
        var name = $(this).data('name');
        $('#searchFilterDiv div.SearchItem.search-results-box-item').each(function(index, object) {
            var names = $(object).data('name').split(/\s*,\s*/);
            if($.inArray(name,names) === -1)
                $(object).hide();
            else
                $(object).show();
        });
    }
    buttons.removeClass('active');
    $(this).addClass('active');
})

Answer №2

When incorporating inline styles in HTML, it's important to note that they will take precedence over other styles unless the important declaration is used.

Furthermore, while using the keyup event listener to retrieve the data-name attribute from each div element and utilizing includes method to search for a specific term, care must be taken to handle case sensitivity since lowercase and uppercase versions may yield different results.

To streamline the functionality and prevent redundancy, it's advised to create a dedicated function named toggleDiDisplay for hiding relevant div elements, as both searching and button click actions serve a similar purpose.

For further optimization, consider refining the function to display all div items if no match is found.

Answer №3

Utilize a loop to iterate through all elements with the class

SearchItem.search-results-box-item
. Check each element's data-name property to see if it includes the selected button's data-name. If it does, display the element; otherwise hide it.

$(document).ready(function() {
  $("#searchInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#searchFilterDiv div.SearchItem").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });

  var btns = $('.filter-button').click(function() {
    if ($(this).data('name') == 'all') {
      $('#searchFilterDiv div.SearchItem').fadeIn(450);
    } else {
      const size = $(this).data('name');
      $('.SearchItem.search-results-box-item').each((i, ele) => {
        const dataNameArr = $(ele).attr('data-name').split(',').map(e => e.trim());
        const matchedEles = dataNameArr.filter(name => name == size);
        if (matchedEles.length > 0)
          $(ele).show();
        else
          $(ele).hide();
      });
    }
    btns.removeClass('active');
    $(this).addClass('active');
  })
});
.service-boxes-centered li {
  min-width: 100px;
  padding-top: .8em;
  padding-bottom: .8em;
  padding-left: 1em;
  padding-right: 1em;
  font-size: .9em;
  margin: .3em;
  color: #4b4b4b;
  text-decoration: none;
  flex-grow: 1;
  text-align: center;
}

.service-box-item {
  border: 1px solid #979797;
  font-size: .8em;
  font-weight: 500;
  cursor: pointer;
  display: inline-block;
  text-align: center;
}

.search-results-box-item {
  border: 1px solid lightgrey;
  margin-bottom: 2em;
  padding: 20px;
  font-size: .8em;
  line-height: 1.3em;
  text-align: left;
  cursor: pointer;
}

.service-box-item.filter-button.active {
  border: red 1px solid !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container form-container">
  <div class="row search-form-item">
    <div class="col-md-12 searchtext-input">
      <h3>search by size: </h3>
      <label for="searchInput" class="sr-only">Search field</label>
      <input class="form-control" id="searchInput" type="text">
      <div class="row service-boxes-centered">
        <ul>
          <li class=" service-box-item filter-button active" data-name="all">All</li>
          <li class=" service-box-item filter-button" data-name="XS">XS</li>
          <li class=" service-box-item filter-button" data-name="S">S</li>
          <li class=" service-box-item filter-button" data-name="M">M</li>
          <li class=" service-box-item filter-button" data-name="L">L</li>
          <li class=" service-box-item filter-button" data-name="XL">XL</li>
          <li class=" service-box-item filter-button" data-name="2XL">2XL</li>
          <li class=" service-box-item filter-button" data-name="3XL">3XL</li>
        </ul>
      </div>
    </div>
  </div>

  <div class="container" id="searchFilterDiv">
    <div class="row">
      <div class="SearchItem search-results-box-item" style="padding-bottom: 2em; display: block;" data-name="M, XL, S, 2XL">
        <h3>flipside</h3>
        <p>Vivamus viverra libero sed mi vehicula euismod. Nullam mauris dolor, hendrerit non lorem nec, vehicula dapibus nisl. In posuere est lectus, consequat tempus velit laoreet ut.</p>
        <p>M</p>
        <p>XL</p>
        <p>S</p>
        <p>2XL</p>
        <br>
      </div>
      <div class="SearchItem search-results-box-item" style="padding-bottom: 2em; display: block;" data-name="M, S">
        <h3>frontside</h3>
        <p>Vivamus viverra libero sed mi vehicula euismod. Nullam mauris dolor, hendrerit non lorem nec, vehicula dapibus nisl. In posuere est lectus, consequat tempus velit laoreet ut.</p>
        <p>M</p>
        <p>S</p>
        <br>
      </div>
      <div class="SearchItem search-results-box-item" style="padding-bottom: 2em; display: block;" data-name="3XL">
        <h3>frontside</h3>
        <p>Vivamus viverra libero sed mi vehicula euismod. Nullam mauris dolor, hendrerit non lorem nec, vehicula dapibus nisl. In posuere est lectus, consequat tempus velit laoreet ut.</p>
        <p>3XL</p>
        <br>
      </div>
    </div>
  </div>

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

When I choose a nested object in my array, the values returned are not consistent

Why is there a discrepancy in the results when both are pulled from the exact same array? The array is passed through a component and is stored as a React state. const [vars, setVars] = useState([]); <Message index={vars.findIndex((entry) => entry.N ...

The tabs are visible in the drawer, but the transition is not occurring

I am a beginner when it comes to using material ui. After clicking on advanced sports search, a drawer pops up. I have been trying to incorporate tabs in the drawer, but every time I click on tab two, the drawer closes. In reality, it should switch between ...

Utilizing CSS Grid to dynamically stretch and wrap rows based on adjacent siblings within a flat DOM structure

Looking for a way to create a grid layout that adjusts row sizes based on adjacent siblings. Interested in SCSS or CSS solutions using grid, flexbox, or other techniques. https://i.sstatic.net/Ump5U.png I am working with a dynamically generated list base ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

Displaying the information fetched using axios on the screen using node.js

Is there a way to display the information from the input boxes in the image on the screen using node js? ...

The Problem of Restoring Column Height in Tabulator 4.6.3 Filters

The Issue After activating and deactivating header filters, the column height does not return to its original state. Is this the expected behavior? Is there a way to reset the column height? Check out this JS Fiddle example: https://jsfiddle.net/birukt ...

Switch out the HTML content within the JavaScript include

Here is the situation: <script type="text/javascript" src="http://xy.com/something.js"></script> This code snippet in my PHP/HTML file loads the entire something.js file. Inside that file, there are lines containing "document.write..." which ...

Form comments in Bootstrap are causing rows to shift

Currently, I am working on an Angular-powered horizontal form that utilizes various bootstrap components. However, I have encountered an issue with a "Comment field" that is causing the adjacent columns to shift downwards. I initially suspected the problem ...

The callbacks from using Mongoose findById() only yield results for irrelevant information

I am currently using Mongoose for database operations. I am experiencing an issue where the findById() method is sometimes returning results, but not consistently: Case 1: Invalid Query models.Repo.findById("somefakeid", function(err, result){console.log ...

Angular filtering options based on user input and model selection

In the jsbin demo provided, there is an input field, a select option, and a list of movies. The objective is to filter the list of movies in Angular based on user input in the input field and selection in the select dropdown. <div ng-controller="myCont ...

How to Send Javascript DOM Value to Inner HTML

I am trying to extract a value from a hidden element ID and set it as the inner HTML for another element ID. Below is my code: <script> function replaceText(){ var x=document.getElementById("mainTitle1").textContent; document.getElementById("mainTi ...

How to implement an external font in AngularJs

I am developing a multilingual website with AngularJS and need to load a font using a .woff file. However, I only want to load the font when it corresponds to the specific language being used on the site. function init(lang){ if(lang == 'eng') ...

Showing nested routes component information - Angular

I am working on a project that includes the following components: TodosComponent (path: './todos/'): displaying <p>TODO WORKS</p> AddTodosComponent (path: './todos/add'): showing <p>ADD TODO WORKS</p> DeleteTo ...

Combine linear and radial background effects in CSS styling

I am trying to achieve a background design that includes both linear and radial gradients. The linear gradient should display a transition from blue to white, while the radial gradient should overlay a polka dot pattern on top of it. I have been following ...

Could anyone lend a hand in ensuring that my AJAX call successfully processes the parameters?

When attempting to retrieve specific data from my database using AJAX, I encountered an issue where the call was successful when made through Postman or directly in the browser, but failed when initiated from my client. It seemed to work intermittently, re ...

What is the best way to update React State after making an asynchronous call to MongoDB?

I have been facing a common issue, but couldn't find an up-to-date solution on Stack Overflow specifically for React/Meteor. My goal is to query a mongoDB to retrieve data and then pass it into the state of my React components. Currently, I am queryin ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

Remove the input box for submission from the HTML code

How can I remove the 'button' from my input field and replace it with an image? Even after trying different methods, the box still appears. Thank you. <!DOCTYPE html PUBLIC ""> <head> <style> #PlusMinus{background:url(&apo ...

What could be causing webpack to struggle in locating the loader?

Check out my package.json: { "name": "redux-todo", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "webpack-dev-server" }, "devDependencies": { "babel": "^6.5.2", "babel-loader": "^6.2.5", "bab ...

Can a nofollow attribute be added to concealed modal content in Bootstrap?

Query: I am dealing with a situation where I have a significant amount of disclaimer text within a modal on my website. This text is initially hidden (display:none) until a user clicks a button to reveal it. I want to prevent search engines from indexing t ...