Exploring the world of real-time search functionality using jQuery for instant suggestions

I have a live search feature with jQuery on my website. The search works fine and displays results, but when I click on a result, I want the value to be shown in my input field. Additionally, once I click outside of the input field, the result should hide (like an autocomplete feature), but I've been struggling to implement this functionality.

I cannot use an autocomplete plugin because I need to display images in my search results.

$(document).ready(function() {
  $("#srehberText").keyup(function() {

    // Retrieve the input field text and reset the count to zero
    var filter = $(this).val(),
      count = 0;
    if (!filter) {
      $(".commentlist li").fadeOut();
      return;
    }

    var regex = new RegExp(filter, "i");
    // Loop through the comment list
    $(".commentlist li").each(function() {

      // If the list item does not contain the text phrase, fade it out
      if ($(this).text().search(regex) < 0) {
        $(this).hide();

        // Show the list item if the phrase matches and increase the count by 1
      } else {
        $(this).fadeIn();
        count++;
      }
    });
  });
});
ol {
  list-style-type: none;
  padding: 0;
  width: 600px;
}

input {
  width: 600px;
  padding: 12px;
  border: 1px solid #ccc;
  color: #999;
}

li {
  display: none;
}

li img {
  margin-right: 5px;
}

li a {
  display: block;
  text-decoration: none;
  color: #666;
  font: 16px tahoma;
  padding: 4px;
}

li a:hover {
  background: #fffff0;
  color: #333;
}
<input type="text" class="text-input" id="srehberText" placeholder="Start typing the region" />
<ol class="commentlist">
  <li>
    <a href="#"><img src="region-image-url-here">Germany</a>
  </li>
  <li>
    <a href="#"><img src="region-image-url-here">Russia</a>
  </li>
  <li>
    <a href="#"><img src="region-image-url-here">Turkey</a>
  </li>
  <li>
    <a href="#"><img src="region-image-url-here">England</a>
  </li>
  <li>
    <a href="#"><img src="region-image-url-here">Netherlands</a>
  </li>
  <li>
    <a href="#"><img src="region-image-url-here">USA</a>
  </li>
  <li>
    <a href="#"><img src="region-image-url-here">Korea</a>
  </li>
</ol>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Answer №1

Here are two options I created for you to try based on your code. Hopefully, they will assist you in achieving your desired outcome.

Option 1 - Single select:

$(document).ready(function() {
  $("#srehberText").keyup(function() {

    var filter = $(this).val(),
      count = 0;
    if (!filter) {
      $(".commentlist li").fadeOut();
      return;
    }

    var regex = new RegExp(filter, "i");
    $(".commentlist li").each(function() {
      if ($(this).text().search(regex) < 0) {
        $(this).hide();
      } else {
        $(this).fadeIn();
        count++;
      }
    });
  });
});

$('.commentlist li a').click(function(){
  $('.commentlist').fadeOut();
  $("#srehberText").val($(this).text())
})

Option 2 - Multi select:

$(document).ready(function() {
  $("#srehberText").keyup(function() {
    var filter = $(this).val(),
      count = 0;
    if (!filter) {
      $(".commentlist li").fadeOut();
      return;
    }

    var regex = new RegExp(filter, "i");
    $(".commentlist li").each(function() {
      if ($(this).text().search(regex) < 0) {
        $(this).hide();
      } else {
        $(this).fadeIn();
        count++;
      }
    });
  });

  // Additional functionality for multi-select
  var clicked = false;
  $('.commentlist li a').click(function() {
    var val = $("#srehberText").val();
    if (!clicked) {
      val = "";
      clicked = true;
      $("#srehberText").val($(this).text())
    } else {
      $("#srehberText").val(val + " " + $(this).text())
    }
  })

  $(document).click(function(event) {
    if (!$(event.target).closest('.commentlist, #srehberText').length) {
      if ($('.commentlist').is(":visible")) {
        $('.commentlist').hide();
      }
    }
  })
});

The script above includes functionality that hides the ol element when clicking outside of .commentlist and #srehberText.

Answer №2

Hopefully this will suffice.

$(document).ready(function() {
  $("#srehberText").keyup(function() {

    // Get the text from the input field and reset the count
    var filter = $(this).val(),
      count = 0;
    if (!filter) {
      $(".commentlist li").fadeOut();
      return;
    }

    var regex = new RegExp(filter, "i");
    // Iterate through the comment list
    $(".commentlist li").each(function() {

      // If the item does not contain the text, fade it out
      if ($(this).text().search(regex) < 0) {
        $(this).hide();

        // Show the item if the phrase matches and increment the count
      } else {
        $(this).fadeIn();
        count++;
      }
    });


  });
  $(".commentlist li a").click(function() {
    var val = $(this).text();
    $("#srehberText").val(val);
    $('.commentlist li').fadeOut();
  });
});
ol {
  list-style-type: none;
  padding: 0;
  width: 600px;
}

input {
  width: 600px;
  padding: 12px;
  border: 1px solid #ccc;
  color: #999;
}

li {
  display: none;
}

li img {
  margin-right: 5px;
}

li a {
  display: block;
  text-decoration: none;
  color: #666;
  font: 16px tahoma;
  padding: 4px;
}

li a:hover {
  background: #fffff0;
  color: #333;
}
<input type="text" class="text-input" id="srehberText" placeholder="Start typing the region" />
<ol class="commentlist">
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">Germany</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">Russia</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">Turkey</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">England</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">Netherlands</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">USA</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">Korea</a>
  </li>
</ol>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Answer №3

$(document).ready(function() {
  $(".commentlist li").click(function(){
     $("#srehberText").val($(this).text());
     // An input box is available and only text can be entered inside.
     // To display an image control beside the input, a small image control needs to be placed
  });
  $("#srehberText").keyup(function() {

    // Get the input field text and reset the count to zero
    var filter = $(this).val(),
      count = 0;
    if (!filter) {
      $(".commentlist li").fadeOut();
      return;
    }

    var regex = new RegExp(filter, "i");
    // Iterate through the comment list
    $(".commentlist li").each(function() {

      // If the list item does not contain the text phrase, fade it out
      if ($(this).text().search(regex) < 0) {
        $(this).hide();

        // Show the list item if the phrase matches and increment the count by 1
      } else {
        $(this).fadeIn();
        count++;
      }
    });


  });
});
ol {
  list-style-type: none;
  padding: 0;
  width: 600px;
}

input {
  width: 600px;
  padding: 12px;
  border: 1px solid #ccc;
  color: #999;
}

li {
  display: none;
}

li img {
  margin-right: 5px;
}

li a {
  display: block;
  text-decoration: none;
  color: #666;
  font: 16px tahoma;
  padding: 4px;
}

li a:hover {
  background: #fffff0;
  color: #333;
}
<input type="text" class="text-input" id="srehberText" placeholder="Begin typing the region" />
<ol class="commentlist">
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">Germany</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">Russia</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">Turkey</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">England</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">Netherlands</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">USA</a>
  </li>
  <li>
    <a href="#"><img src="https://cdn2.iconfinder.com/data/icons/seo-flat-6/128/39_Email_Marketing-16.png">Korea</a>
  </li>
</ol>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Answer №4

Another option is to utilize the select feature, explore it here

Answer №5

To hide a list when clicking somewhere else:

<input type="text" onblur="hideList()">

<script>
var mouseOverList = false; //mouse-over list
// create events for mouseover and mouseout to change the value of mouseoverlist

function hideList() {
    if (mouseOverList == false) { 
        // code to hide the list goes here 
    }
}
</script>

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

Strategies for sending data in the body of a GET request in a React.js API

I'm having an issue passing data in the body of a GET type API request in my React.js app. Here is the code I am using, but the API isn't receiving any data. getUnits = ( key, text, code, limit, offset ) => { let data = JSON.st ...

Is it possible to transfer .NET backend functions to a frontend framework like React or Vue for client-side execution?

For instance, imagine a scenario where there is a login page requiring a username and password to meet specific criteria for validation: the username must contain a capital 'A' and the password should be exactly 8 characters long. The challenge l ...

Storing input field values in JavaScript using the onchange event handler.Would you like a different revision

I am looking to calculate the area by multiplying width and height entered into input fields, and then display the result. Any guidance would be greatly appreciated. Thank you! Here is my current code. const width = document.querySelector("#width"); con ...

Achievement with ajax: If the status code is 200, execute one function; otherwise, execute a

I can't figure out why this isn't working... I'm using $.ajax to run file.php and pass a POST value from an input field. Even though the file.php is functioning properly (it successfully adds a user to my newsletter), my ajax function seems ...

Utilizing JSON and Javascript to dynamically generate and populate interactive tables

Here's how I've structured my JSON data to define a table: var arrTable = [{"table": "tblConfig", "def": [{"column": "Property", "type": "TEXT NOT NULL"}, {"column": "Value", "type": "TEXT NOT NULL"}], "data": [{"Property ...

Issue with bottom margin on the last flex item located at the end of the container is not being applied

My button is currently touching the end of the container, but I want to create some space between them. However, adding a margin bottom to the button does not seem to be working as expected. Below is the CSS and HTML code: .events{ height: 100%; d ...

Is the process.env.NODE_ENV automatically set to 'production'?

While examining someone else's code, I noticed this particular line. if (process.env.NODE_ENV === 'production') { ... The application in question is a node.js app with express server and reactjs front-end. If we were to deploy it on Heroku ...

Select2 script fails to render properly after returning from Action Result

In my MVC4 application, the index page features JQuery UI tabs that I use to display content updated via Ajax action links. One of the tabs includes a Select2 option box which renders correctly initially but defaults to basic functionality after clicking a ...

Adjust the size of an element in response to changes in the size of

I've implemented a jQuery function to resize an element dynamically based on window size changes: $(window).resize(function() { topHeight = $("#top").height(); height = $(window).height() - 210; $("#container").height(height); $("#g").height( ...

JavaScript enables logging on Android Emulator

Currently, I am working with an Ionic app that is connected to SalesForce Mobile SDK. Due to the lack of support for the SDK and certain plugins in Ionic Serve, I have resorted to running the app in Android Studio using an Emulator - specifically, the Andr ...

Exploring Variable Naming in Angular with Dynamic Scope

Is there a way to avoid using large IF statements in my controller when working with fields/models that have similar logic but different scope variable names? I'm looking for a solution to dynamically append numbers to the scope variable names in Angu ...

Error encountered while trying to render a Threejs FBX Object - undefined 404 (Resource not found)

I am facing an issue while loading a set of .fbx objects using FBXLoader on a WebXR App. window.fbxLoader.load("/assets/modelate_FBX/Vaza%208067134/Vaza 8067134.fbx", function( object ) { const flower = this.scene.children.find(c => c.name ...

What is the best way to eliminate a blank array in JavaScript?

After countless hours of searching, I am reaching out for help with an issue that has me stumped. My Node.js application relies on JSON files for project configurations. Using the 'fs' module, I read the JSON file, parse it into a JavaScript obje ...

Deleting a pair of files from a folder before exiting

In my program, I am trying to remove all .csv files that are generated in the directory upon program exit, as well as a file named "less" without an extension. Despite successfully removing all .csv files, the "less" file is not being deleted from the dire ...

Divide the row once you've reached the end of the container

I am facing an issue with the code snippet provided below where the images fetched from the database seem to break the DIV and cause an overflow. My goal is to have the images break and start a new line once they reach the end of the DIV. Unfortunately, ...

Evolving the appearance of every vacant element

Currently, I am working on a project that allows users to add items. To facilitate this process, I have included an "add another" button which enables them to include additional items all at once. In order to validate the form and save values to the datab ...

Converting a Google font for compatibility with ThreeJS: A beginner's guide

Is there a way to convert a downloaded Google font from TTF to JSON in order to use it with ThreeJS FontLoader / TextGeometry? import LatoFont from '../assets/fonts/lato-bold.json' const loader = new FontLoader(); const font = loader.parse(LatoF ...

combine various types of wrappers in React

We're embarking on a fresh project with React, and we will be utilizing: React Context API i18n (react.i18next) GraphQL (Apollo client) Redux CSS-in-JS (styled-components or aphrodite) The challenge lies in each of these implementations wrapping a ...

Can anyone explain why my inner div's display is set to block and it is being pushed down when its parent div has

Below is a sample of my HTML+CSS code: <div> <div class="first">text</div> <div>more text</div> </div> div { display: inline; } .first { display: block; } What's interesting is that when the first ...

"Encountering a challenge with accessing the class or id of an HTML element following the retrieval of data from an

Having trouble accessing the id or class of the label fetched from PHP... Here is my code snippet: $.ajax({ type:'POST', url:"<?php echo base_url(); ?>main/user_list", data:"", async:false, success: ...