Having trouble with autocomplete suggestions in jquery not functioning as expected?

Currently, I am working on an autocomplete component using jQuery UI. Although the autocomplete function is working correctly, I am facing an issue where typing the letter "I" displays all the list items available from JSON data, whereas I only need to show relevant matches like "India", "Indonesia", etc. Additionally, I would like to limit the displayed values to a maximum of 10 in the list. I have made some updates to the code by attempting to use slicing in the autocomplete functionality to achieve this and then display the selected value in the next textbox.

Below is the latest jQuery code snippet:

$("#ipt_Countryres").autocomplete({
 source: function( request, response ) {
      var regex = new RegExp(request.term, 'i');
    $.ajax({
        url: "json/countries.json",
        dataType: "json",
        data: {term: request.term},
        success: function(data) {
            response($.map(data, function(item) {
                if(regex.test(item.label)){
                    return {
                        id: item.id,
                        label: item.label,  
                        value: item.value
                    };
                }
            }));
        },
        minlength:2,
        select: function (event, ui) {
           $("#get_country").val(ui.item.label);               
       }
    });
}

});

Here is the corresponding HTML code:

<input type="text" id="ipt_Countryres" name="ipt_Countryres" class="ipt_Field"/>
<input type="text" class="ipt_Field" id="get_country" name="get_country"/ disabled>

Sample JSON data used:

[  
   {  
    "value":"Afghanistan",
     "label":"Afghanistan",
     "id":"AF"
   },
   {  
      "value":"Åland Islands ",
     "label":"Åland Islands",
     "id":"AX"
   },
   // Additional JSON data entries...

Your assistance in resolving this matter is greatly appreciated.

Thank you in advance.

Sincerely, Mahadevan

Answer №1

Here is a suggestion:

var countryArray = [  
  {  
    "id":"Afghanistan",
    "label":"Afghanistan",
     "value":"AF"
  },
  {  
  "id":"Åland Islands ",
  "label":"Åland Islands",
  "value":"AX"
   },
 {  
    "id":"Albania ",
    "label":"Albania",
    "value":"AL"
 }]
$("#ipt_Countryres").autocomplete({
   minLength:1,
    source: function(request, response) {
    var filteredCountries = $.map(countryArray, function(country) {
        if( country.id.startsWith(request.term)){
            return country;
        }
        else{
            return null;
        }
    });
  
  filteredCountries = filteredCountries.slice(0,10);
  
    response(filteredCountries);
},
   select: function(event, ui) {
     event.preventDefault();
     // Prevent value from being put in the input:
     $('#ipt_Countryres').val(ui.item.label);
     $('#get_country').val(ui.item.label);
     // Set the next input's value to the "value" of the item.
   },
  
  focus: function(event, ui) {
        event.preventDefault();
         $('#ipt_Countryres').val(ui.item.label);
    }
  
});
<link href="http://api.jqueryui.com/jquery-wp-content/themes/jquery/css/base.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.8.24/jquery-ui.min.js"></script>


<input type="text" id="ipt_Countryres" name="ipt_Countryres" class="ipt_Field"/>
<input type="text" class="ipt_Field" id="get_country" name="get_country"/ disabled>

Answer №2

To enhance your filtering capabilities using regex, consider integrating the following code snippet:

$.ui.autocomplete.filter = function (array, term) {
   var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
   return $.grep(array, function (value) {
     return matcher.test(value.label || value.value || value);
   });
};

For more information, check out this resource: jqueryui-autocomplete-filter-words-starting-with-term

Answer №3

To increase the number of results, try adjusting the minLength setting:

$("#ipt_Countryres").autocomplete({
    source: country_list,
    minLength: 3,
    max:10,
    select: function (event, ui) {
        // Ensure only label is inserted into input:
        $('#ipt_Countryres').val(ui.item.label);
        $('#get_country').val(ui.item.label);
        // Assign item value to next input field.
    }
});

Here is the code in action:

JS Fiddle : http://jsfiddle.net/abcdef12/

Answer №4

Thank you for sharing your suggestion!

Presenting to you my latest output.

$("#ipt_Countryres").autocomplete({
highlightClass: "bold",
 source: function( request, response ) {

      var regex = new RegExp(request.term, 'i');

      //var filteredArray = filteredArray.slice(0,10);
    $.ajax({
        url: "json/countries.json",
        dataType: "json",
        data: {term: request.term},
        success: function(data) {
            response($.map(data, function(item) {
                if(regex.test(item.label)){
                    return {
                        id: item.id,
                        label: item.label,  
                        value: item.value
                    };
                }
            }));
        }  
    });
},
minlength:3,
select: function (event, ui) {
    $("#get_country").val(ui.item.label);
}

});

Many thanks and best regards, Mahadevan

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 it possible to invoke a function located in the 'code behind' using AJAX in ASP.NET WebForms?

Is there a way to access a method in code behind when clicking on a span in an aspx view? CODE IN DEFAULT.ASPX VIEW: <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"> <%-- SPAN ELEMENT --%> <span runat="ser ...

Struggling with passing data to a child component in React

I am currently working on a gallery project where users can click on an image to view it in a separate component using props. The images are sourced from a hardcoded array, and the challenge lies in connecting this data to the component accurately. I have ...

Unable to utilize a variable for accessing an array element within a field

What is the reason I am unable to use a variable to access something inside my document? It seems that hard coding the field works, but when using a variable, it does not yield the expected result. building = "AS" room = "243" item = "whiteBoard.votes[0 ...

Jquery form submission is failing, and a JavaScript warning appears in the console stating that 'body.scrollLeft is deprecated in strict mode' instead

In my JavaScript file, I've written the following code: function PS_SL_HandleEvent() { $(document).ready(function() { $('#form').removeAttr('onsubmit').submit(function(e) { if(acceptCGV()) { ...

The automatic opening of a modal in a Livewire component is not functioning as expected

I am having trouble displaying a modal when my component initializes. I have tried using $this->emit('show) to open the modal When I add a button in my view, the emit('show') works! However, I want the modal to be automatically shown whe ...

Tips for displaying res.locals information in the console for debugging purposes using ExpressJS and Nodejs

Currently, I am delving into the world of Node.js and ExpressJS as a novice in this realm. My primary requirement is to log the entire or partial content of res.locals in my console for debugging purposes. Here's what I've attempted: var foo_ro ...

I am facing issues connecting my Express Node server to my MongoDB database using Mongoose

Starting my backend journey, I keep encountering the same error with my server.js --> // Step 1 - Create a folder named backend // Step 2 - Run npm init -y // Step 3 - Open in VS Code // Step 4 - Install express using npm i express // Step 5 - Create se ...

Header that stays fixed at the top within a collapsible accordion layout

I'm experimenting with creating an accordion-style layout that transitions to an accordion on smaller screens, as shown by resizing the snippet attached to this question. I'm using flex to establish a sticky header, which is currently only applie ...

Questions regarding prototype-based programming in Javascript

I am interested in achieving the following using Javascript: function A(){ this.B = function() { ... }; this.C = function() { <<I need to call B() here>> } ; }; I came across a method of method overloading, but I am curious to know ...

What is the best way to make "inline-block" elements move to a new line when needed?

Check out my fiddle: #container { background-color: green; } .result { border-radius: 6px; display: inline-block; width: 100%; max-width: 160px; min-width: 100px; height: 160px; border: 1px solid black; background-color: white; marg ...

Exception Thrown When Element is Not Visible in Robot Framework

I encountered an ElementNotVisibleException error, even though the element appeared to be visible based on the screenshot in the logs. The button is controlled by JavaScript and can switch between enabled and disabled states. Here's the code for the d ...

Utilizing Jquery for precise element placement and retrieving its position details

Within my bundle of jQuery code, there are a few areas where I am experiencing difficulties trying to recall functions. The following is an excerpt of the code: $(document).ready(function(){ $("#myTablePager").html(""); $.ajax({ type: "POS ...

Loading external scripts prior to component loading in Vue.js

Within my Vue project, I have the need to fetch a script from a server location (e.g. https://myurl.com/API.js). This script contains a variable that I intend to utilize within my Vue component/view. The issue arises when I attempt to load this script usi ...

What is the best way to align an element in the middle of a div when there is another element in

I am trying to center an element within a div while another element is positioned nearby. Using text-align: center gets the element close to where I want it, but not exactly due to the presence of another element. My goal is to have the logo element center ...

Implementation of chained if-else if statements using dot.js

Exploring the doT.js template engine and wondering about the nested if-else if syntax in dot.js. How can we achieve it in a structure like this: if() ..... else if ..... else if ..... else ..... ...

Unveiling the JSON data hidden within nested arrays on Android: A step-by-step guide

I received a JSON result and I am trying to extract the text value from the duration array. How can I achieve this? { "routes" : [ { "bounds" : { "northeast" : { "lat" : 19.0759817, "lng" : 80.27 ...

Switch on/off all checkboxes in an Angular group

I am working on a table that contains text-checkbox items, each with a description and a checkbox. Now, I'm looking to add a master checkbox that can toggle the state of all the checkboxes at once. Below is the current code snippet, along with my init ...

Issue with the statement not being recognized for counting the space bar

I created a counter but I'm having trouble incorporating if statements For example: if (hits == 1) {alert("hello world1")} if (hits == 2) {alert("hello world2")} if (hits == 3) {alert("hello world3")} if (hits == 4) {alert("hello world4")} This is t ...

Error: Cannot set value on a property that is designated as a getter-only in Vue.js using

My current task involves taking an image as input, converting it into a base64 string, preparing a payload containing the base64 string, and sending a post request to the backend. I then need to retrieve the response data and preview the base64 image from ...

Searching for MongoDB / Mongoose - Using FindOneById with specific conditions to match the value of an array inside an object nestled within another array

Although the title of this question may be lengthy, I trust you grasp my meaning with an example. This represents my MongoDB structure: { "_id":{ "$oid":"62408e6bec1c0f7a413c093a" }, "visitors":[ { "firstSource":"12 ...