Sort through a list of items by the key input when characters are removed from the input field, ensuring that the color remains constant

<ul class="locationlist list-unstyled">
<li>
<div class="checkbox checkbox-success">
<input id="checkbox1" type="checkbox">
<label for="checkbox1">
Vijayanagar
</label>
</div>
</li>
<li>
<div class="checkbox checkbox-success">
<input id="checkbox2" class="test" type="checkbox">
<label for="checkbox2">
Indiranagar
</label>
</div>
</li>
<li>
<div class="checkbox checkbox-success">
<input id="checkbox3" type="checkbox">
<label for="checkbox3">
Rt Nagar
</label>
</div>
</li>
<li>
<div class="checkbox checkbox-success">
<input id="checkbox4" type="checkbox">
<label for="checkbox4">
Rajajinagar
</label>
</div>
</li>
<li>
<div class="checkbox checkbox-success">
<input id="checkbox5" type="checkbox">
<label for="checkbox5">
HSR Layout
</label>
</div>
</li>
<li>
<div class="checkbox checkbox-success">
<input id="checkbox7" type="checkbox">
<label for="checkbox7">
Basavanagudi
</label>
</div>
</li>
<li>
<div class="checkbox checkbox-success">
<input id="checkbox8" type="checkbox">
<label for="checkbox8">
Marathahalli
</label>
</div>
</li>
<li>
<div class="checkbox checkbox-success">
<input id="checkbox10" type="checkbox">
<label for="checkbox10">
Malleswaram
</label>
</div>
</li>
<li>
<div class="checkbox checkbox-success">
<input id="checkbox11" type="checkbox">
<label for="checkbox11">
Banashankari
</label>
</div>
</li>
</ul>
<script>
$(document).ready(function(){
     $('.serchfild').keyup(function(){
    var value = $(this).val();
    $("ul.locationlist > li .checkbox label").each(function() {
        if ($(this).text().search(new RegExp(value, "i")) > -1) {

            $(this).parents('.checkbox').show();
            if($(this).text().search(new RegExp(value, "i"))){
                $(this).css('color','red');
            }

        }
        else {
            $(this).parents('li').hide();
        }

    }); });
});

filter the list items based on input keyup. After clearing all characters in the input field, the color doesn't change. If I press one character in the input field, only that character should change color. If I clear the input field, display all the list items. Fiddle link

Answer №1

Hey there! Take a look at what I've created here

HTML

    <input type="text" id="search-dinosaurs" placeholder="Search for Dinosaurs (start typing)" />

<ul id="dino-list">
  <li>Diplodocus</li>
  <li>Stegosaurus</li>
  <li>Triceratops</li>
  <li>Pteradactyl</li>
  <li>Tyrannosaurus Rex</li>
  <li>Protoceratops</li>
  <li>Iguanadon</li>
  <li>Velociraptor</li>
</ul>

and JS

$(document).ready(function () {

    /* initially hide product list items */


    /* highlight matches text */
    var highlight = function (string) {
        $("#dino-list li.match").each(function () {
            var matchStart = $(this).text().toLowerCase().indexOf("" + string.toLowerCase() + "");
            var matchEnd = matchStart + string.length - 1;
            var beforeMatch = $(this).text().slice(0, matchStart);
            var matchText = $(this).text().slice(matchStart, matchEnd + 1);
            var afterMatch = $(this).text().slice(matchEnd + 1);
            $(this).html(beforeMatch + "<em>" + matchText + "</em>" + afterMatch);
        });
    };


    /* filter products */
    $("#search-dinosaurs").on("keyup click input", function () {

        if (this.value.length > 0) {
            $("#dino-list li").removeClass("match").hide().filter(function () {
                return $(this).text().toLowerCase().indexOf($("#search-dinosaurs").val().toLowerCase()) != -1;
            }).addClass("match").show();
            highlight(this.value);
            $("#dino-list").show();
        }
        else {

           //$("#dino-list, #dino-list li").removeClass("match").hide();
          $("#dino-list, #dino-list li").removeClass("match");
          $("#dino-list, #dino-list li").show();
           $("#dino-list li").removeClass("match").hide().filter(function () {
                return $(this).text().toLowerCase().indexOf($("#search-dinosaurs").val().toLowerCase()) != -1;
            }).addClass("match").show();
            highlight(this.value);
        }
    });


});

and CSS

input[type=text]{
  width:200px;
  padding:8px 10px;
}

li em {
  background:#ff6;
  font-weight:bold;
  font-style:normal;
}

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

Filtering elements upon loading

I have successfully implemented data filtering on my website using data-filter. While everything is working great, I am interested in displaying items with specific attributes upon loading. For instance, I want to load only green objects by default inste ...

Increasing a local variable in the view using ASP.NET

Despite its seeming simplicity, I'm struggling to find the solution to this problem. When adding a number (like 2) to a page variable, it's being recognized as a string and displaying: instead of 3 : 1+2 @{ var page= 1 ; } <li>@ ...

What could be causing jQuery submit to navigate to its own page even when the action is pointed to a different page

I have the following form on my settings.asp page, designed to submit to sendmail.asp. However, when I click the button, I notice in the console that it is triggering settings.asp instead of sendmail.asp. I've checked and confirmed that both the form ...

How to Change Text When Accordion is Expanded or Collapsed using Javascript

Help needed with JavaScript accordion menu for displaying indicators in front of section headers. The goal is to show a (+) when collapsed and (-) when expanded. The current code only changes on click, not based on the section's state. Looking for fre ...

How to perfectly center a text box in HTML

UPDATE: I have included the relevant JavaScript code. Essentially, a text box appears when a checkbox is clicked, but I want the text box to be centered on the page. I am attempting to center align a text box on the page, but I am struggling to achieve th ...

Add and remove text boxes dynamically with jQuery, retrieve the value of the dynamic text box, and show it in another text box

I have a code snippet that allows you to dynamically add or remove textboxes using the .append() and .remove() functions in jQuery. Now, I am looking to concatenate all the values of the textboxes with commas separating them and then pass this combined val ...

Excessive Blank Areas

I needed to create 3 horizontal paragraphs side by side, and the only solution I found was using the position property, but it didn't turn out as expected. Despite my efforts to make it look clean, it always ends up like this. Below is the code I use ...

Position the image on top of the details

I have an image with a spinner rotating around it through animation, accompanied by two boxes containing information as depicted in the uploaded image below. However, I would like to position the image above the boxes rather than beside them. .about-img ...

What is the process for loading an HTML form into a specific target using Angular?

Is there a way to load an HTML form into a target in Angular without the use of jQuery? I have a working script, but I am currently stuck on: <html> <head> <script src="components/angular/angular.js"></script> <script&g ...

Chrome leak when rounded border in `overflow:hidden` parent is exceeded

Even with a rounded parent element, the hidden part of a child element continues to appear in Chrome: In Internet Explorer, adding the CSS property z-index to the parent element can solve this issue. However, this solution does not work in Chrome. #con ...

Unable to use jQuery change function within Bootstrap 5 tabs

I have inserted an input form within the tabs of bootstrap 5 like so: <div class="container"> <div class="row justify-content-center my-5"> <div class="col-auto"> <ul class="nav bg-dark&qu ...

Creating an SQL select statement with a three-level expression is a complex task that requires careful planning and

How can I create a SQL select query with 3 levels of expressions and statements? Typically, my website operates on an SQLite database and the search results are displayed using the following SQL query: "SELECT DISTINCT * FROM amz WHERE Title LIKE \" ...

The push action in NavController is not displaying Google Maps as expected

Trying to display a map upon clicking a button is proving challenging for me. It appears that the function NavController.push() does not work as expected, while NavController.setRoot() does. Despite not encountering any errors, I am unable to identify the ...

Unveil SQL Limit with a Simple Scroll Load

After successfully laying out and creating my website, the next step is to load more results on scroll. This question has been posed numerous times before, but I am curious if there is a simple solution that can seamlessly integrate into my current setup. ...

Once the user clicks on the download button, the backend should initiate the download process

I am seeking a solution where a download can be triggered in the background when a download button is clicked, without interrupting other tasks. Is there a way to achieve this in PHP? If so, what method can be used? I have attempted using the curl function ...

Activate inactive html button using javascript

One of the challenges I am facing is testing forms where the client specifically requested that the submit button be disabled by default. I have been exploring ways to dynamically replace the disabled="" attribute with enabled using JavaScript within a s ...

Bind a function to the final element of each piece of changing content

I'm facing a challenge in associating a function with every nth element, just once for each element. The concept is to trigger an ajax call when the final element comes into view. I am utilizing a useful jquery plugin called inview. My list consists ...

Ways to enlarge a YouTube thumbnail upon loading using JavaScript

I recently found a solution to my question on how to prevent YouTube videos from repeating even when different embedded codes are used. I have a specific need to resize the thumbnail image of my YouTube video to width:146px and height:124px when the page l ...

How to effectively position a div in CSS into two columns

I am currently facing an issue with positioning a div when one post contains a lot of text. The div seems to be expanding to accommodate the extra text, causing layout problems. You can view my code here. HTML <div class="container"> <div> ...

What is a reliable method for automatically refreshing a webpage despite encountering server errors?

I'm working on an HTML+JS web page that refreshes itself automatically every few seconds using http-equiv="refresh". The problem is, sometimes the server returns a 502 "bad gateway" error, preventing the HTML code from loading and causing th ...