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

Getting the Right Value: A Step-by-Step Guide to Setting the Default or Selected Value in

When creating directive form controls (text, select, radio), I am passing a value to the directive function. If this value is not set or empty, then the default value should be taken from the question data._pageAttributes.defaultValue. HTML <div ng-re ...

Error: Unable to call topFrame.window.changeSelectedBarStyle because it is not a valid function. What could be causing this

This function is called changeSelectedBarStyle: function changeSelectedBarStyle(tdId){ $("#menuTable td").each(function(index){ if(this.id == tdId){ $(this).removeClass("menuPanel"); $(this).addClass("menuPanelSelected" ...

Switch between displaying the HTML login and register forms by clicking a button

Currently, I am working on a website that requires users to either log in or register if they do not have an account. Below is the code I have developed for the login page: <span href="#" class="button" id="toggle-login">Log in</span> <di ...

Applying CSS onmousemove does not function properly in conjunction with Bootstrap framework

Currently, I have a code snippet that enables an absolutely positioned box to follow the movement of the mouse cursor: $(document).mousemove( function(e) { $(".wordbox").css({ top: "calc(" + e.pageY + "px - 0.8em)", left: e.pageX }) ...

Error received when attempting AJAX call with jQuery 1.7.2: NS_ERROR_XPC_NOT_ENOUGH_ARGS

Encountering an issue with jQuery version 1.7.2 and the ajax function. When running the code snippet below, Firefox Firebug console displays the following error: NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace] var wei ...

Utilize Vue.js to easily upload images alongside form input fields

I have recently started a small project with Vue Js. I am trying to incorporate an upload file option in my contact form. Due to the numerous input text fields, I am using serialize for the form. However, I am facing issues with the append function. How ca ...

conversion of text to number using JavaScript

After pulling values from an XML file using JavaScript, I face the challenge of converting a string to an integer in order to perform calculations. To extract data from the XML file, I use the following snippet: var pop = JSON.stringify(feature.attribute ...

transferring a JavaScript variable to PHP upon submitting a form

This question arises after my previous inquiry on the topic of counting the rows in an HTML table using PHP. Since I didn't find a solution that worked for me, I am exploring new methods but struggling with the implementation. My approach involves ass ...

Is there a feature similar to Google/YouTube Insight called "Interactive PNGs"?

Recently, I have been exploring the YouTube Insight feature and I am intrigued by how their chart PNGs are generated. When you view the statistics for a video, the information is presented in interactive PNG images. These images seem to be entirely compos ...

Retrieve a single instance of every element within an array using JavaScript

I have an array of player objects, each containing properties such as "position" and "player_name". With 8 unique positions available for players, I aim to extract the first player for each position and transfer them to a new array. This way, the new array ...

What are some ways to utilize symbol fonts such as marvosym within a web browser?

Are you looking to use special LaTeX fonts like \Pluto from marvosym in your web development projects? Wondering how to display this symbol with HTML / JavaScript / CSS without relying on an image? You can download the font from This symbol corresp ...

My code gets disrupted when I use classes instead of IDs

My HTML code works fine when I use IDs and select them in my javascript with getElementByID. However, if I switch to using classes instead of IDs, my code stops working. I want to switch to using classes because I am collaborating on a project with someon ...

The utilization of the jquery.form.js plugin is resulting in my form being submitted twice

In order to enable Ajax file uploads in my ASP.Net MVC project, I am utilizing the jquery plugin known as "jquery.form.js" (http://malsup.com/jquery/form/#getting-started). However, I am encountering an issue where the controller action responsible for han ...

Navigate back to the previous page upon form submission to a PHP file, with a div dynamically populated with targeted content

I'm facing a logic dilemma: I have a webpage with a div called #content, where I've embedded another page containing a form for submitting data* (there are other pages loaded into #content as well, but they are not active at the same time, one o ...

Is it possible to apply a consistent character width to all glyphs, even the most obscure Unicode symbols, using CSS?

Is it possible to style a single character within a span element to have a specific width and height of 1em? Ideally, I would like the character to be stretched if it is not already fixed-width. This styling must support any character, including rare Unic ...

Troubleshooting Issue: Failure of Ajax Script to Display Saved Data in Edit Function

Whenever I clicked on the Edit icon in the action column of my data tables, the saved data did not display as expected. I noticed that this issue was only occurring for file input types, while it worked properly for text input types. In the Blade file Ad ...

Having trouble creating a unit test for exporting to CSV in Angular

Attempting to create a unit test case for the export-to-csv library within an Angular project. Encountering an error where generateCsv is not being called. Despite seeing the code executed in the coverage report, the function is not triggered. Below is the ...

The JQuery error encountered was due to a missing colon after the property ID

I'm currently working on some jQuery code that is supposed to hide one paragraph and show another when a specific action is triggered. I have created a class called "showp" which displays the targeted paragraph while ensuring that other paragraphs are ...

Generating JSON data from Dom elements within a specified `div` container

My goal is to extract all the elements from within a div element, which may consist of multiple inputs, checkboxes, radiobuttons etc. After that, I want to convert the id or name and value attributes into a format that can be read as JSON. I attempted to ...

What is the method for extracting a list of properties from an array of objects, excluding any items that contain a particular value?

I have an array of objects, and I want to retrieve a list with a specific property from those objects. However, the values in the list should only include objects that have another property set to a certain value. To clarify, consider the following example ...