Javascript Input Datalist keep adding options

I have a table in the database with all the cities (about 41.000), I need the user to select one. When the chars in the input are >3, the datalist gets filled but the result can’t get selected.

I made an API call in PHP that gives a JSON to the javascript which fills the datalist. Every time the event is triggered the datalist keeps geetting filled, duplicating the results.

I know I’m missing a part of code for sure. I used some tutorials and this problem was not mentioned. What should I do? I paste some code below.


<input name="locationFrom" id="locationFrom" type="text" class="form-control" required="required" autocomplete="off" list="countriesFrom-<?=$i?>" onkeyup="findCity(this.value, <?=$i?>)">
<datalist id="countriesFrom-<?=$i?>"></datalist>


function findCity(citySearch, j){
  if (citySearch.length > 3) {
      url: './api/country/find.php?city=' + citySearch,
      type: 'GET',
      contentType: 'application/json; charset=utf-8',
      dataType: 'JSON',
      success: function(response){
          var len = response['records'].length;
          var countries = response['records'];
          for(var i=0; i<len; i++){
              var city = countries[i].city;
              var region = countries[i].region;
              var country = countries[i].country;
              $("#countriesFrom-" + j).append($("<option >").attr('value', city)
                .text(city + ", " + region + ", " + country));


Answering my own question, but maybe useful for someone:

every time the chars are > 3 I do:

  if (citySearch.length > 3) {
    var countries = [];
    document.getElementById(elementId).innerHTML = '';

Where elementId is of course my datalist.