Link to home
Start Free TrialLog in
Avatar of Omar Martin
Omar MartinFlag for United States of America

asked on

AutoComplete would not work on search box

I have a search field which provides data from a database for the user. It works well but the autocomplete coding doesn't.  The station names are suppose to automatically show. Please see the code below...

<h3>Search Box</h3>
    <label>Type Station Name</label>
    <input id = "stationBox" type="text">
    <ul id="autoList"></ul>
    <button id ="stationOne" >Submit</button>
    <div id="searchResult"></div>

Open in new window


//Inserting information in a search bar--
<script>
  $(document).ready(() => {
    $('#stationOne').click(() => {
      var requestUrl = 'stationNames/' + $('#stationBox').val();
      console.log('making ajax request to', requestUrl)
      $.ajax({
          url:requestUrl,
          type:'GET',
          datatype:'json',
          success: (data) => {
          console.log('You received some', data);
            
          var search_data = '';
            $.each(data, function (key, value) {
              //console.log(value.ID);
              search_data += '<li>ID: ' + value.ID + '</li>' +
                '<li>Station: ' + value.Station + '</li>' +
                '<li>Address: ' + value.Address + '</li>' +
                '<li>Sales: ' + value.Monthly_CStore_Sales + '</li>' +
                '<li>Operator: ' + value.Operator + '</li>' +
                '<li>Top SKU: ' + value.Top_SKU + '</li>' +
                '</<li>' + '<br/>';
            });

            $('#searchResult').html(search_data);
          }
      })
    });
  });
         // Autocomplete for search bar
           $(document).ready(function(){
           $('#stationBox').keyup(function(){
              $('#autoList').html('');
              var searchField = $('#stationBox').val();
              var expression = new RegExp(searchField,"i");
              $.getJSON('/alldata', (data) => {
              $.each(data, function (index, value) {
                console.log(value.Station);
                if(value.Station.search(expression) != -1)
                {
                  $('autoList').append('<li>'+value.Station+'</li>');                
                }
              })
            });
          });
        });
</script>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Zakaria Acharki
Zakaria Acharki
Flag of Morocco image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Omar Martin

ASKER

Thank you Zakaria......I will seek to follow your advice. I have a question. When I copy your code, below.....I am getting the error: value is not defined. I normally do a ajax call on every event but I know that is not necessary but how can I save the value variable inside a function to call it again when I need it?  I tried to put it in a function, but it doesn't seem to work for me.

$('#stationBox').on('input', () => {
         $('#autoList').html('');
var searchField = $('#stationBox').val();
         var expression = new RegExp(searchField, "i");
   
         if( searchField.length ){
         console.log(value.Station);
         if (value.Station.search(expression) != -1) {
          $('#autoList').append('<li>' + value.Station + '</li>');
        };
      }
        });
  });
Hi Omar, You're welcome,

You were so close, you need just to loop through the stationsInfos list that we filled in the getData() function when the page is loaded the first time, from there we can get the "key, value":

  $('#stationBox').on('input', () => {
    $('#autoList').html('');
    var searchField = $('#stationBox').val();
    var expression = new RegExp(searchField, "i");

    if( searchField.length ){
      $.each(stationsInfos, function(index, value) {
        if (value.Station.search(expression) != -1) {
          $('#autoList').append('<li>' + value.Station + '</li>');
        }
      });
    }
  });

Open in new window


Here's the version of getData() function that you need to store the data just one time in stationsInfos for the later use:

function getData(stationsInfos){
  $.getJSON('/alldata', (data) => {
    $.each(data, function (index, value) {
      stationsInfos[value.ID] = value;
    });
  });
}

Open in new window

Zacharia: Your global variable works great except there is a problem with the autocomplete.  It only remembers the station name or it only autocompletes when you have put in a station in the input box and enter it's results at least once.  It doesn't autocomplete if you are entering the station name for the first time.

Any suggestions?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you. I had a simple error......it's fixed now....and works........just curious, I'm use to the traditional autocomplete where the options for autocomplete shows up in the input box and cascades vertically......

Is there another format for this?