Explore the Filter List without being affected by the arrangement of words or the level of search precision

I was able to resolve the issue by adjusting my search filter algorithm. Now, I can search regardless of word order, but the results are not as specific as I need them to be. When I type "Correy" in the search bar, it shows all results containing that word correctly. However, when I try to search for a specific "Correy Adele", it still displays all "Corey" results. This is not what I want. Any suggestions on how to improve this?

function updateResults() {

var keywords =  $('input').val().toUpperCase().split(' ');
var listItems = $('li');
var link;
var ul;
var textValue;
ul = document.getElementById("myUL");
for (var i = 0; i < listItems.length; i++) {
    link = listItems[i].getElementsByTagName("a")[0];
    textValue = link.textContent || link.innerText;
    for(var j = 0; j < keywords.length; j++) {
        if (textValue.toUpperCase().indexOf(keywords[j]) > -1 ) {    
            listItems[i].style.display = '';
           // no need for further matches
        } else {
            listItems[i].style.display = 'none';
        }
        break;
    }
}

}
<style>
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" onkeyup="updateResults()" placeholder="Search for names.." title="Type in a name">

<ul id="myUL">
  <li><a href="#">Adele Correy</a></li>
  <li><a href="#">Agnes Green</a></li>

  <li><a href="#">Billy Correy</a></li>
  <li><a href="#">Bob Green</a></li>

  <li><a href="#">Calvin Green</a></li>
  <li><a href="#">Christina Correy</a></li>
  <li><a href="#">Cindy Correy</a></li>
</ul>

Answer №1

To optimize the process, consider introducing a new variable and initializing it as true. Then, iterate through the filter words while checking if each word is included in the text value. Finally, based on the match result, toggle the display property of the list item element accordingly.

var isMatch = true;

for (var f = 0; f < filter.length && isMatch; f++) { // exit loop if no match
    isMatch = txtValue.includes(filter[f]);
}

li[i].style.display = isMatch ? '' : 'none';

function myFunction() {
  var filter = $('input').val().toUpperCase().split(/\s+/); 
  var li = $('li');
  var a = $('a');
  var ul;
  var txtValue;
  ul = document.getElementById("myUL");
  var isMatch
  
  
  for (var i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = (a.textContent || a.innerText).toUpperCase();
    
    isMatch = true;

    for (var f = 0; f < filter.length && isMatch; f++) {
        isMatch = txtValue.includes(filter[f]);
    }

    li[i].style.display = isMatch ? '' : 'none';
  }
}
<style>* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px;
  /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<ul id="myUL">
  <li><a href="#">Adele Correy</a></li>
  <li><a href="#">Agnes Green</a></li>

  <li><a href="#">Billy Correy</a></li>
  <li><a href="#">Bob Green</a></li>

  <li><a href="#">Calvin Green</a></li>
  <li><a href="#">Christina Correy</a></li>
  <li><a href="#">Cindy Correy</a></li>
</ul>

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

Removing an element that is floated inside a parent element with other floated and non-floated siblings in Chrome

Can someone help me with this code issue? <!doctype html> <title>Test case</title> <div style="float: left"> <div style="float: left;">Short.</div> <div></div> <div style="overflow: hidden;"&g ...

Here is an example of how to use a script tag to check the value of a select tag in HTML:

Hi there! I'm working on a piece of code where I need to retrieve the selected value from a dropdown menu in an HTML select tag and display it in the element with the id='h1' at the bottom. The script tag is already included within the head ...

When communicating with the backend in a React application, the data is not being successfully sent using axios. An error message stating "Unsupported protocol

My current setup involves using Express.js as the backend and setting up a proxy to the backend in the package.json file of my React.js project. Initially, I encountered an error when using the fetch method, so I switched to using Axios to resolve this iss ...

jQuery random generator for creating two-dimensional arrays

Why do all rows always have the same numbers? They should be populated with random numbers. Also, how can I fix this issue? I remember seeing a solution here before but now I can't seem to locate it. var mapSizex = 5; var mapSizey = 6; var mapArray ...

What are the indicators of JSON in a response?

When using ReactJS to make a fetch request to an API, the JSON body response includes the following: { "place": <a href=\"http:\/\/place.com\/ search?q=%23MILKYDOG\" target=\"_blank\">#milkydog<&b ...

Tips for triggering a JavaScript function within WordPress using an inline function call

While setting up my plugin in the WordPress admin area, I encountered an issue with a form that stores user information. In my file input type, there is a JavaScript function call to my custom JavaScript that I have linked. Here is the line of code causing ...

How to submit the next row using jQuery AJAX only when the previous submission is successful without using a loop - could a counter

Currently, I am dealing with loops and arrays. My goal is to submit only the table rows that are checked, wait for the success of an Ajax call before submitting the next row. Despite trying various methods, I have not been successful in achieving this yet. ...

Does shutting down a window with code in Jquery Post/AJAX impact the server script?

Let me start by acknowledging that this may not be the most straightforward question to address. I've got a PHP script that typically takes around 5-10 minutes to complete. I'd prefer not to make the user wait for it to finish. So, if I initiate ...

Styling with CSS in Zend Framework

In the process of creating a website using Zend Framework, I have successfully implemented the header, footer, and all the necessary pages. However, I am facing an issue with integrating the CSS file located at public/css/styles.css. When running the webs ...

Using a variable in Ajax URL with Action razor syntax

I have a function that calls a method in the controller through an Action URL. However, I need to use a parameter as the name of the method, but unfortunately, this is not possible in the current implementation. function changeDropDownList(id, dropNameToC ...

CSS and JavaScript Nav Menu Collapse (No Bootstrap)

I have written a navbar code using pure HTML/SASS, but I am facing a challenge in adding a collapse element to the navigation bar. Despite trying various solutions from Stack Overflow, I still haven't found one that works for me. Therefore, I am rea ...

Nested elements not transitioning using CSS

Why is my transition not being applied to the submenu <a> tag? The color change is working fine, but the transition does not occur on hover. When I use the same rules on another element with a different main class, it works perfectly. It seems like t ...

timer-based user session expiration

Currently, the app I'm developing has a system where a session is created with a 15-minute expiration time once a user interacts with a form. This session is managed server-side. If the user remains idle for 15 minutes, the server returns a 404 erro ...

A Comprehensive Guide on Implementing String Values in Highchart Series

When attempting to pass a string value (data) to the highchart series, I encountered an issue where it would display a blank chart. Is there a specific way to use a string value in the series of the highchart jQuery plugin? var data="{name: 'Jane&apo ...

Fill your background with a stunning background image

I have encountered a common issue where the existing solutions do not seem to solve my problem. The background image I am working with is taller than it is wide, and I want its height to be 100% of the body's height. To achieve this, I attempted the f ...

Tips for implementing a draggable image within an <a-scene> by utilizing <a-assets> and <a-image> tags

Exploring the world of augmented reality for the web has been an interesting journey for me. I have been experimenting with aframe-ar.js and aframe.js to create a unique experience. One of the challenges I faced was making an image draggable within the & ...

Navigate Formik Fields on a Map

Material UI text-fields are being used and validated with Formik. I am looking for a way to map items to avoid repetitive typing, but encountering difficulties in doing so. return ( <div> <Formik initialValues={{ email: '&a ...

Unlocking the power of python with web2py by tapping into html form values

I'm working on a project using web2py and need to incorporate ajax/javascript with a form. Currently, when a user selects an option in the departure box, the arrival box appears. However, I'm unsure of how to filter the list of arrival options ba ...

Guide on extracting JSON data from jQuery containing an array in C#

Looking for a way to extract array data from JSON in C#? Here is an example of the AJAX code: $.ajax({ type: "GET", url: "/Weather/GetWeather", data: { "a": ["1,","2&"], "b" : 4 }, success: onSc ...

Is there a way to launch iframe links in the parent window of an Android native app?

I'm currently working on developing a directory-style application, and I am using iframes to embed other websites into the app. I would like the embedded site links to open within the parent window. In the Progressive Web App version, everything is w ...