Searching for li elements that contain text values - a guide

I have a list of letters and I want to filter out any values that contain the text entered by the user in a textbox.

Here is the design:

Search List:

<input type="text" id="txtSearch" />

<ul>
  <li>Coffee1</li>
  <li>Coffee2</li>
  <li>Tea1</li>
  <li>Tea2</li>
  <li>Milk1</li>
  <li>Milk2</li>
</ul> 

For example: If the user enters 'k1' in the textbox, I want to only display Milk1 & Milk2.

How can this be achieved?

Any help solving this would be greatly appreciated!

Answer №1

Here is a method to filter list elements based on user input. Whenever the input changes, all list elements are hidden and only those containing the typed string are displayed:

$('#txtSearch').on('input', function() {
     var userInput = this;
     $(this).next('ul').find('li').hide().filter(function() {
         return $(this).text().indexOf(userInput.value) > -1;
     })
     .show();
});

$('#txtSearch').on('input', function() {
     var userInput = this;
     $(this).next('ul').find('li').hide().filter(function() {
         return $(this).text().indexOf(userInput.value) > -1;
     })
     .show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtSearch" />

<ul>
  <li>Coffee1</li>
  <li>Coffee2</li>
  <li>Tea1</li>
  <li>Tea2</li>
  <li>Milk1</li>
  <li>Milk2</li>
</ul> 

REMEMBER. Using the input event also works for pasted input.

Ref: .filter( function )

Answer №2

By utilizing the :contains() selector, you can easily filter content on a webpage. Check out this fiddle for an example.

Here is the key code snippet:

$('#txtSearch').keyup(function(){
  $('li').hide();
  $('li:contains('+$(this).val()+')').show();
})

If you need the search to be case-insensitive, you can modify it like shown in this example. In that fiddle, we introduce a custom :Contains() selector as demonstrated below:

jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
    return function( elem ) {
        return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

Simply use the newly created :Contains() selector instead of the standard :contains() selector.

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

Refresh the webpage source code for an AJAX request

When using AJAX calls on a page, I have noticed that the page source remains unchanged. This can be problematic if a user performs forward/backward operations in their browser, as the browser will display the original HTML code instead of the updated conte ...

Enable express to disregard specific URL modifications

I'm currently working on creating a Single Page App using Express. One of the challenges I am facing is that the Express route feature forces the view to be re-rendered every time the URL changes and a GET request is sent to the server. My code typica ...

DANGEROUS EVALUATION: Tips for Safe Replacement

Looking for a safer alternative to the code below which utilizes eval. The script creates pop-up windows based on different classes. /* exported popup_default , popup_help , popup_sitemap , popup_footerlinks */ var matchClass = ['popup_default' ...

Most effective method for streamlining conditional checks in JavaScript

To enhance the quality of my code and improve its readability, I have decided to implement a currying functions approach and create pure helper functions for repetitive code snippets. One issue I noticed was the frequent existence/type checks throughout my ...

Change events are not being received upon clicking the radio buttons

Hey friends, I'm trying to set up backbone events for when radio buttons are clicked. Here are the radio buttons I have: <p><label for="pays">Pays now</label><input id="pays" name="pays" type="radio" value="1" class="_100"/>&l ...

Halt hovering effect after a set duration using CSS or Vanilla JavaScript

Looking for a way to create a hover effect that lasts for a specific duration before stopping. I want the background to appear for just 1 second, even if the mouse remains hovering. Preferably using CSS or JavaScript only, without jQuery. To see my curren ...

Listcell XUL with button options

How can I make buttons inside a listcell function in XUL? I am having trouble getting it to work. Here is the XUL code: <listitem id = "1"> <listcell label = "OK Computer"/> <listcell label = "Radiohead"/> <listcell label ...

Looking to bookmark Java links or a similar task?

Apologies for the lackluster title, as I am not well-versed in programming language and struggle to articulate my specific request... Allow me to explain: I frequently need to visit a particular website to conduct research (details below). I attempted usi ...

Tips for detecting a false return value from a jQuery AJAX script

I am currently utilizing jQuery and AJAX to perform form validation when a new user is being created on my website. My development environment consists of OOP PHP in conjunction with jQuery and AJAX. Here is the code snippet I am using: $.ajax({ ...

No spaces are being retrieved from the input field

After entering "test data" in the first input box and clicking the submit button, only "test" is displayed in another input box. The goal is to have "test data" appear in the script-generated input box as well. Sample HTML Code <input name="" type="te ...

React's setState() not reflecting state changes when clicked

I have developed a component that displays data from a Redux store grouped by week. To ensure the week's relevance is maintained within this component, I decided to store its value in local state as shown below: constructor(props) { super(props ...

Having trouble getting a background image with tint to display properly in Bootstrap

I applied a sleek black transparent gradient to my body background picture, but as soon as I integrated bootstrap into the HTML code, the effect ceased to function. body { background: linear-gradient( rgba(0, 0, 0, 0.5), rgba ...

Choosing a Query with Puppeteer - Unleashing the Power of Selection in Puppeteer

How do I use Puppeteer to select the html anchor element that clicks and navigates to the Tutorial page? https://i.sstatic.net/6rkNn.png I've tried this but it's not working const puppeteer = require('puppeteer'); const url = process ...

The type 'true | CallableFunction' does not have any callable constituents

The error message in full: This expression is not callable. No constituent of type 'true | CallableFunction' is callable Here is the portion of code causing the error: public static base( text, callB: boolean | CallableFunction = false ...

Arranging rows of a specific height within a table at any location

I need to create a virtual table to browse through a very large dataset. Is there a way to position the rows (with fixed height) anywhere within the table? The issue I am facing is that the table properties automatically adjust the row height, disregarding ...

Experiencing the Pause: A Fresh Take on

I'm currently using this slideshow for a project, and I need to understand if it's possible to resume its interval. The current issue is that when you hover over the slideshow, the progress bar stops. But once you remove the mouse, it continues f ...

Renew the Look of Dynamic HTML with Updated Styles

In the middle of my website, there is a console that contains links to dynamically update its content using javascript. Everything works smoothly, but the new HTML added dynamically does not have any styling applied to it. Is there a way to refresh the CS ...

Is it possible to use only CSS to crop an image into a square and then shape it into

I am attempting to create a circular shape out of images that have varying sizes and shapes (some rectangular, some square, some portrait, and some landscape). When I apply either clip-path: circle(50% at 50% 50%); or border-radius: 50%;, the image transf ...

Dynamic Search Functionality using Ajax and JavaScript

function fetchData(str) { if (str.length == 0) { var target = document.querySelectorAll("#delete"); return; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && ...

Tips for implementing a toggle feature for an ion-card element

I am looking to create a toggle effect on ion-card, where clicking on the card will highlight it until either unclicked or another card is clicked. Similar to this - How can I achieve this effect on ion-card? Here is my HTML code - <ion-grid> ...