Ensure that the search box produces identical results for both the input "abc123" and "abc 123"

This dropdown search box is functioning flawlessly..... However, I want the option "Contact us" to display the same result whether someone searches for "contactus" or "contact us". In both cases, the outcome should be identical. I prefer not to add two separate options for this scenario. Please assist!

/* Function to toggle between hiding and showing the dropdown content when button is clicked */

function hideOptions() {
  document.getElementById("myDropdown").classList.remove("show");
}

function showOptions() {
  hideOptions();
  document.getElementById("myDropdown").classList.add("show");
}

function filterFunction() {
  var input, filter, div, a, i;
  input = document.getElementById("myInput");
  if( input.value === ''){
      hideOptions();
      return false;
  }
  filter = input.value.toUpperCase();
  div = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i < a.length; i++) {
    txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      a[i].style.display = "";
    } else if(a[i].classList.contains('fixed-input') === true) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }
  showOptions();
}
.div {
  display: none;
}

.dropbtn {
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

#myInput {
  box-sizing: border-box;
  background-position: 14px 12px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 14px 20px 12px 45px;
  border: none;
  border: 5px solid #ddd;
}

#myInput:focus {
  outline: 7px solid #ddd;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f6f6f6;
  min-width: 230px;
  overflow: auto;
  border: 1px solid #ddd;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
<div class="dropdown">
  <input type="text" class="dropbtn" placeholder="Search Here..." id="myInput" onkeyup="filterFunction()">
  <div id="myDropdown" class="dropdown-content">
    <a href="#about">About</a>
    <a href="#base">Base</a>
    <a href="#blog">Blog</a>
    <a href="#contact">Contact</a>
    <a href="#custom">Custom</a>
    <a href="#support" class="fixed-input">Support</a>
    <a href="#tools">Tools</a>
    <a href="#tools">Cyber Warriors YouTube Channel</a>
  </div>
</div>

Answer №1

One suggestion is to implement the startsWith method for better functionality.

I made a modification to the code as follows:

if (txtValue.toUpperCase().indexOf(filter) > -1)

replacing it with:

if (txtValue.toUpperCase().startsWith(filter) || filter.startsWith(txtValue.toUpperCase()))

/* Toggle between displaying and hiding dropdown content when user clicks button */

function hideOptions() {
  document.getElementById("myDropdown").classList.remove("show");
}

function showOptions() {
  hideOptions();
  document.getElementById("myDropdown").classList.add("show");
}

function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  if( input.value === ''){
      hideOptions();
      return false;
  }
  filter = input.value.toUpperCase()
  div = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i < a.length; i++) {
    txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().startsWith(filter) || filter.startsWith(txtValue.toUpperCase())) {
      a[i].style.display = "";
    } else if(a[i].classList.contains('fixed-input') === true) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }
  showOptions();
}
.dropbtn {
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

.div {
  display: none;
}

#myInput {
  box-sizing: border-box;
  background-position: 14px 12px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 14px 20px 12px 45px;
  border: none;
  border: 5px solid #ddd;
}

#myInput:focus {
  outline: 7px solid #ddd;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f6f6f6;
  min-width: 230px;
  overflow: auto;
  border: 1px solid #ddd;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
<div class="dropdown">
  <input type="text" class="dropbtn" placeholder="Search Here..." id="myInput" onkeyup="filterFunction()">
  <div id="myDropdown" class="dropdown-content">
    <a href="#about">About</a>
    <a href="#base">Base</a>
    <a href="#blog">Blog</a>
    <a href="#contact">Contact</a>
    <a href="#custom">Custom</a>
    <a href="#support" class="fixed-input">Support</a>
    <a href="#tools">Tools</a>
    <a href="#tools">Cyber Warriors YouTube Channel</a>
  </div>
</div>

Answer №2

Utilizing REGEX can help accomplish this task

var userInput = document.getElementById('userInputField')
var userText = userInput.value // userText = 'sample text'
userText = userText.replace(/\s+/g,'') // userText = 'sampletext'

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

Chrome browser experiences a glitch with its calendar function

This form is designed to be simple for users. They are prompted to enter their name and select their gender in a specific order. When they click the calendar button, the calendar will display and then hide again. Please note that this feature only works ...

Sorting can be done in a table that is scrollable

Can someone recommend a sortable table with scrolling and a fixed header? I'm looking for a solution that can be implemented using either jQuery or plain JavaScript. Your input is greatly appreciated. Thank you! ...

Determine the number of times a user has accessed a page on my website

Is there a way to track how many times a user loads pages on my website using JavaScript? Could it be done like this? var pageLoads = 1; $(document).ready(function(){ var pageLoads ++; }); Should I store this information in a cookie? ...

Ways to stop a hyperlink from executing on confirmation cancel using jquery

I'm having trouble with a link that should not perform any action when the cancel button is clicked. I've attempted to use false in the click event and also tried using e.preventDefault, but I'm unsure if I am implementing it correctly. Can ...

Issue with JAWS screen reader failing to announce aria-expanded status

My aim is to ensure that the collapsed state is accessible in both NVDA and JAWS, but I am encountering issues with it displaying properly in JAWS. Does anyone have any suggestions on how to rectify this? I have included images of the code and link list b ...

How to implement a "callWhenReady" function in JavaScript

I am new to javascript and currently working on restructuring my prototype code. The current setup involves multiple levels of nested callbacks, making it difficult to read and manage. I am aiming for a cleaner approach similar to the following: GoogleMap ...

Utilizing nested grouping in mongoose schemas

I am facing a challenge while attempting to execute a nested group query in MongoDB. Is there a way to group data by both date and campaign ID, ensuring that each campaign ID contains a nested array of creatives with their respective data (views and clicks ...

Why is the React Util js file not functioning properly when using an absolute path?

Help needed! I'm utilizing create-react-app without ejecting. I can't seem to figure out why this code snippet is not functioning correctly. import { capitalizeFirst } from 'util/util.js'; //This line is causing issues import AdminIn ...

A more efficient method for adding HTML content to an element

I have been working on implementing an infinite scroll feature like this: <script type="text/javascript"> $(function () { var page = 1; var $ol = $('#namesList'); var $waypoint = $('#namesWaypoint'); ...

Steps for preloading images in nuxt-dropzone1. Begin by importing the

I am currently utilizing nuxt-dropzone https://www.npmjs.com/package/nuxt-dropzone for image uploads. My goal is to also utilize it as an image library where users can view their uploaded images in a similar fashion. As there isn't much documentation ...

Is it just me or does Img never work, no matter what the "src" is?

I am implementing Google's React example of a "Complex Grid" (located here) to create a Card-like layout. This is how the code appears: return ( <div className={classes.root}> <Paper className={classes.paper} ...

The function Route.delete() expects a callback function, however, it received an [object Undefined] instead

Struggling with an error in my delete function that says "Route.delete() requires a callback function but got a [object Undefined]". Can't seem to figure out what's causing this issue. const playerController = { index: (request, response) ...

Utilizing AJAX and setInterval Techniques for Efficient handling of window.location.hash

//Collecting AJAX links var ajaxLink = $("#logo, .navLink, .tableLink, .footerLink"); //Storing the recent state as null (because there is none yet) var recentState = null; //Initializing the page state based on the URL (bookmarking compatibility) window ...

Converting a TypeScript object into a JSON string

When working with TypeScript, I am facing a challenge while trying to initialize an object that requires a JSON string for the "options" parameter. Specifically, it pertains to the object mentioned here. It is crucial that the options parameter be in JSON ...

Notify when the focus is solely on the text box

How can I display an alert only when the focus is on a text box? Currently, I am getting an alert whenever I skip the text box or click anywhere on the page. The alert even appears when I open a new tab. Is there a way to fix this issue? Thank you for your ...

PHP programming language for opening, editing, and saving HTML files

Trying to use PHP to open an HTML file, remove the content of a specific div (class Areas), and then save it. $dom = new DOMDocument; $dom->loadHTMLFile( "temp/page".$y.".xhtml" ); $xpath = new DOMXPath( $dom ); $pDivs = $xpath->query(".//div[@class ...

Why does the element from a nested array in javascript return as undefined when I try to access it?

Struggling to extract elements from a multidimensional array in JavaScript. Running into an issue where attempting to access elements from arrays within the main array using a variable results in undefined. Surprisingly, I achieve the desired outcome whe ...

Is there a way to extract the text from the inner div of an element using nightwatch.js?

I'm attempting to retrieve the content of a cell within a table, with the following CSS structure: <div data-testid="cellvalue_row-1_col-0" class="Table-cellContent" xpath="1"><span data-testid="tableCellCon ...

Ways to convert an asynchronous operation to synchronous in JavaScript

Currently in the process of developing an eslint plugin, I have come across a particular issue. My goal is to implement real-time changes to the configuration file by making an HTTP request to retrieve the JSON configuration. When attempting to execute co ...

Running on Node.js, the Promise is activated, yet there remains an issue with the function

I've encountered a strange issue that I can't seem to diagnose. It's showing a TypeError: My code is returning 'function is undefined', which causes the API call to fail. But oddly enough, when I check the logs and breakpoints, it ...