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

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Filtering out specific properties from an element within a JavaScript forEach loop

const findBloodType = bloodCodeArray.find(bloodCode => bloodCode.code.toUpperCase() === bloodType.toUpperCase()).code; In my Angular code, I am trying to retrieve just the 'code' property of the 'bloodCode' element using a callback ...

I am preparing for a quiz and I am in need of a diverse set of random questions, without any repetition

I am facing a major issue with my PHP script. I need to fetch random questions from a MySQL database and display them like the example here: . Additionally, I am looking to have an admin dashboard to manage questions and users. You can find my current scri ...

Is there a way to retrieve JSON data from a different domain and incorporate it into my own website?

I am attempting to utilize JSON data from "" and display the data on my website. My goal is to extract the JSON field name "Stats" and retrieve the sub-field name '\"v\"'. You can refer to the documentation provided by purpleair here: h ...

Is there a way to automatically insert page numbers into every internal link on an HTML page?

When in print mode, I want to display links like this: <a href="#targetPage">link</a> but I'd prefer them to appear as: <a href="#targetPage">link (page 11)</a> (assuming the target page is on page 11 in the print preview). ...

Transferring an IONIC project to a different computer

Let me outline the current situation I am facing - I primarily work as a firmware developer rather than a software developer. Recently, a team member who was responsible for developing the front end of an application in IONIC has left the company, leaving ...

Creating a large and spacious modal in Angular using ngx-bootstrap

I need help with resizing the ngx-modal to cover a large area of the screen. Currently, I am trying to make it so that when something is clicked, the modal should overlay an 80% width grid on a full desktop screen. Despite my attempts at using .modal-xl an ...

I want to locate every child that appears after the <body> element, and extract the HTML of the element containing a specific class within it

It may sound a bit confusing at first, but essentially I have some dynamically generated HTML that resembles the following: <body> <div class="component" id="465a496s5498"> <div class="a-container"> <div class="random-div"> ...

Material-inspired Design Device Compatible DIV slide with JS, JQuery, and CSS

My goal is to achieve something similar to this: Desired Live Website I am looking for a feature where clicking on the div will slide in content from the right, load an external page inside it, and close when prompted. The slider div should be device c ...

Adding margin to an HTML element causes the entire page to shift downward

Despite successfully applying margin to other elements, I encountered an issue with #searchbarcontainer where it causes the entire page to shift downward. My goal is to center it slightly below the middle of the page, but I'm struggling to find a solu ...

Conceal the choice if its value matches that of another option

My goal is to create a code that will hide an <option> if its value matches the value of the first option (which is retrieved dynamically with PHP). Here's the initial code snippet: <select onChange="this.form.submit()" name="cart[<?php e ...

Promise.all does not wait for the inner Promise.all to complete before continuing

let dataObj = [ { Id: 1, name: 'Alice', Address:[{ city: 'Paris', country: 'France' }] }, { Id: 2, name: 'Bob', Address: [{ city: 'NYC', country: &a ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

Change the color of this element and input field background

Having trouble with setting the background color of an input field to red in this code: $(document).ready(function(){ $(".abc").focus(function(){ $(this).attr('background', 'red'); $("label").text('Insert tex ...

Implementing asynchronous validation in Angular 2

Recently started working with Angular 2 and encountered an issue while trying to validate an email address from the server This is the form structure I have implemented: this.userform = this._formbuilder.group({ email: ['', [Validators.requir ...

Finding the correct column in a drop-down menu based on a table array using AngularJS

In my controller, I have data like this: $scope.operationData = [ { "label" : "Inventory", "labelType" : "Master Tables", "type" : "PROCESSOR", "outputStreams" : 1, "elementType" : "TABLE", "name" : ...

CSS: Creative ways to switch up background hues within a grid layout

Im working on a project with a similar layout to this I am trying to achieve a chessboard effect in my grid layout, where the last element of one row has the same background color as the first element of the next row. I have set up my container using CSS ...

Hide a parent div in jQuery depending on the checkbox status

I have a code snippet that I need help with. You can view the code here. $("#filters :checkbox").change(function() { $(".listing-details > div").hide(); $("#filters :checkbox:checked").each(function() { $(".listing-details ." + $(this). ...

What is the best way to customize the text in the navigation bar at the top of the page

I'm having trouble with the Navigation Bar code in my header. The text is not staying within the header and I can't seem to fix it. Is there a CSS solution to keep the text contained within the header? <div class="header"> <img src= ...

Tips for effectively utilizing the :valid pseudo-class in Material-UI components to dynamically alter the border styling

Currently, I am attempting to adjust the border color of Mui TextFields using createTheme from Mui v5 when the input is valid. The border itself is defined within the ::before and ::after pseudoclasses. For the TextFields, I am utilizing variant="stan ...