Searching dynamically using class names with JQuery

I am seeking to create a dynamic search input based on the class names within the span tags. However, I am struggling with displaying the class name that I have identified. My goal is to show the class names that match the entered value in the input on the screen. Can you assist me with this issue?

jQuery.expr[':'].contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
    .indexOf(m[3].toUpperCase()) >= 0;
};

$(document).ready(function() {
  $("#searchinput").keyup(function() {
    var inputvalue = $("#searchinput").val();
    var spantags = $("#iconlist span");


    if (inputvalue.length == 0) {
      spantags.show();
    } else {
      if (spantags.hasClass(inputvalue)) {
        $("#iconlist span").hide();
      }
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" placeholder="Search" id="searchinput" />

<div id="iconlist">
  <span class="test1">Demo-1</span>
  <span class="test2">Demo-2</span>
  <span class="test3">Demo-3</span>
  <span class="test4">Demo-4</span>
</div>

Answer №1

If you want to display the span where the class matches the input, you can use the following code snippet:

spantags.filter(function() {
  return $(this).attr("class").indexOf(inputvalue) > -1;
}).show();

Check out this demo:

jQuery.expr[':'].contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
    .indexOf(m[3].toUpperCase()) >= 0;
};

$(document).ready(function() {
  $("#searchinput").keyup(function() {
      var inputvalue = $("#searchinput").val();
      var spantags = $("#iconlist span");
      spantags.hide();
      spantags.filter(function() {
        return $(this).attr("class").indexOf(inputvalue) > -1;
      }).show();
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" placeholder="Search" id="searchinput" />

<div id="iconlist">
  <span class="test1">Test-1</span>
  <span class="test2">Test-2</span>
  <span class="test3">Test-3</span>
  <span class="test4">Test-4</span>
</div>

Answer №2

If you are in search of a precise match, for example, "test1", then you can use:

spantags.filter(":not(." + inputValue + ")").hide()

This code snippet instructs to hide elements that do not have the specified class. (If you want to match any letter, like "t", you can utilize .attr("class").indexOf as mentioned in another response.

Here is the updated code snippet:

$(document).ready(function() {
  $("#searchinput").keyup(function() {
    var inputValue = $("#searchinput").val();
    var spantags = $("#iconlist span");

    spantags.show();
    if (inputValue !== "") {
        spantags.filter(":not(." + inputValue + ")").hide()
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" placeholder="Search" id="searchinput" />

<div id="iconlist">
  <span class="test1">Sample-1</span>
  <span class="test2">Sample-2</span>
  <span class="test3">Sample-3</span>
  <span class="test4">Sample-4</span>
</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

Develop an outline using D3.js for the clipath shape

After successfully creating a shape with a color gradient, I encountered the need for further customization. If you are interested in this topic, check out these related questions: Add multi color gradient for different points in d3.js d3.js scatter plot c ...

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...

Look into HTML and JavaScript problems specific to IOS devices

I have encountered some HTML markup and JavaScript functionality issues on my web-app that seem to only occur on iPad and iPhone. Unfortunately, I do not have access to any iOS devices to debug these problems. How can I replicate and troubleshoot these i ...

Animation of CSS with an image depicting a leaf swaying gently in the breeze

This project was a personal challenge for me, and I am quite satisfied with the approach I have developed. However, I am open to exploring alternative methods if there are any. The website I am working on features a logo that includes an image of a leaf. ...

The event is not functioning properly with jquery

<div id="form"> <form action=""> <input type="button" id="sub"/> </form> </div> Upon clicking the submit button, the content will be dynamically changed using jQuery. Here is the jQuery code: $(document).ready(function() { ...

Is there a way to synchronize breakpoint values across different media queries?

Currently utilizing Next.js version 9.53. Utilizing the built-in CSS module support provided by Next.js without the use of CSS pre-processors (less, sass, etc.) or CSS-in-JS (styled-components, etc.). Presently, my approach involves writing CSS in a mobi ...

When viewed on a mobile device, the contact information bar should vertically collapse

Here is the code snippet I am working with: <div class="topbarsection"> <ul> <li class="alignleft"> <a href="#">Office Address</a> </li> <li class="aligncenter"> Office Timings ...

Adjusting the size of an image based on the size of the window

I'm currently working on my first website project. I have successfully implemented a large image banner, however, I am facing an issue with setting its height. Whenever I try to adjust the height using percentage values, the banner disappears. My goal ...

Ways to send information to browser javascript from Spring MVC controller

Looking for the most efficient method to transfer data from Spring MVC to JavaScript. Let's say there is an array in JavaScript: var myArray = new Array(); And in the Java backend, there is another array: int[] myArray = new int[100]; What would ...

Tips on how to decorate a radio button using borders and colors

How can I change the color of my radio button and its border color? I attempted to modify the code below, but it is not producing the desired result. li.payment_method_bacs input[type='radio']:checked:before { background: black !important ...

I am unable to utilize folder paths in CSS within my React application

Having trouble setting a background image in CSS within my React app. When styling and setting the image from a React component, it works just fine. Can anyone provide assistance? This code snippet will work: const style={ width:'300px', ...

AngularJS: Enhancing Date Display and Organization

Looking to change the date format from "Mon Oct 12 2015 00:00:00 GMT+0530 (IST)" to "YYYY/MM/DD" within my controller. ...

Converting the given data into an object in JavaScript: a step-by-step guide

"[{'id': 3, 'Name': 'ABC', 'price': [955, 1032, 998, 941, 915, 952, 899]}, {'id': 4, 'Name': 'XYZ', 'id': [1016, 1015, 1014, 915, 1023, 1012, 998, 907, 952, 945, 1013, 105 ...

Ways to reset the selected option when the user chooses a different option using either Jquery or Vanilla JavaScript

I am currently working on a functionality to clear the select option when a different brand is selected. The issue I am facing is that when I choose another brand, the models from the previous selection are not cleared out. For example, if I select BMW, I ...

Ensure that the <aside> elements span the entire width of their containing parent element

I am currently designing a website and I am aiming for a specific layout. Any advice on how to achieve this would be greatly appreciated. The header of the page consists of: a logo aligned to the left within an <a> tag 2 widgets placed in <asid ...

In all tests, except for the initial one, the DOM is not updated by test-utils once triggers have been fired

I have been facing an issue with checking for error messages related to field completion in HTML/DOM after vuelidate is triggered. The functionality works properly after the click trigger, and all tests pass successfully - including mounting, element searc ...

Challenges encountered in d3.js when parsing through data sets

For the past two days, I have been struggling to solve this error and I'm at a loss. Every time I try to add data to the visualization, I encounter the following error: Uncaught TypeError: Cannot read property 'length' of undefined It seem ...

Having trouble with rendering components in React and Bootstrap?

Attempting to display basic Bootstrap components using React. This corresponds to the index.html file: <!doctype html> <html> <head> <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="j ...

What sets apart ajax calls from getJSON requests?

I am encountering an issue with my Web.API app being served from the URL http://server/application. When I try to pull data from the servers using a GET request on the client side, I am facing unexpected behavior. The following code snippet works as expec ...

Looking to iterate through MongoDB using a promise and a forEach loop? I'm aiming to populate an array

I've been struggling to iterate through elements in my MongoDB database and save the values to an array. Despite putting in hours of effort, I can't seem to get it done. Here's the code snippet: //shopController.js const Product = require ...