1

I use jquery ui autocomplete on a form to autocomplete city and postal code from a text file.

The text file is formatted like this :

FR;24108;Bergerac
FR;24109;Bergerac
FR;24110;Léguillac-de-l'Auche
FR;24110;Saint-Léon-sur-l'Isle
FR;24110;Manzac-sur-Vern

The autocomplete works on the corresponding field but I would like when user choose a postal code to fill automatically the city in the field city.

And this is where where it doesn't work. I've tried to create an object with label / value :

autoCompleteData.push({cp: values[1]+'', city: values[2] + ''})

If I do a console.log(), I can see my object but I have difficulty to use it in order to use it in response needed by jquery ui autocomplete. I've seen some examples based on json response but I don't know how to adapt this to my needs. I've also tried to convert my object to json but doesn't work.

Could your explain me how to do this ?

Here is my working code

 $.ajax({
                url: "path-to-file/ZipCodes.txt?id=1",
                dataType: "text",
                success: function (data) {
                    var autoCompleteData = data.split('\n');
                    var lines = data.split(/\r\n|\n/);

                    //Set up the data arrays
                    var autoCompleteData = Array();
                    for (var j = 0; j < lines.length; j++) {
                        var values = lines[j].split(';'); // Split up the comma seperated values
                        //postcodes.push(values[1], values[2]);
                        autoCompleteData.push(values[1] + '');
                        //autoCompleteData.push({cp: values[1], city: values[2] + ''});
//console.log(autoCompleteData[0][1]);
                $("#edit-code-postal").autocomplete({
                    source: function (request, response) {
                        var results =     $.ui.autocomplete.filter(autoCompleteData, request.term);
                        response(results.slice(0, 10)); // Display the first 10 results
                    },
                    // We fill the city field
                    select: function (event, ui) {
                        // here I need help to use my object
                    }

                });
            }
        });

And a working snippet without Ajax since I can't load my file on SO. I juste use an array instead :

$(document).ready(function() {
  var data = [
    "FR;24001;Périgueux",
    "FR;24002;Périgueux",
    "FR;24100;Saint-Laurent-des-Vignes",
    "FR;24100;Lembras",
    "FR;24100;Bergerac"
  ];
  //var autoCompleteData = data.split('\n');
  var lines = data;

  //Set up the data arrays
  var data1 = [];
  var data2 = [];
  var data3 = [];
  var autoCompleteData = Array();

  //var headings = lines[0].split(';'); // Splice up the first row to get the headings

  for (var j = 0; j < lines.length; j++) {
    var values = lines[j].split(';'); // Split up the comma seperated values

    //postcodes.push(values[1], values[2]);
    autoCompleteData.push(values[1] + '');
    //autoCompleteData.push({cp: values[1], city: values[2] + ''});

  }

  //console.log(autoCompleteData[0][1]);
  $("#edit-code-postal").autocomplete({
    source: function(request, response) {
      var results = $.ui.autocomplete.filter(autoCompleteData, request.term);
      response(results.slice(0, 10)); // Display the first 10 results
    },
    // On remplit aussi la ville
    select: function(event, ui) {
      $('#edit-ville').val(ui.item.city);
    }

  });
});
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
</head>

<body>

  <div class="ui-widget">
    <label for="tags">Postal code (try "24...": </label>
    <input id="edit-code-postal">
    <label for="tags">City: </label>
    <input id="edit-ville">
  </div>


</body>

</html>

                    }
                    //console.log(autoCompleteData[0][1]);
                    $("#edit-code-postal").autocomplete({
                        source: function (request, response) {
                            var results = $.ui.autocomplete.filter(autoCompleteData, request.term);
                            response(results.slice(0, 10)); // Display the first 10 results
                        },
                        // On remplit aussi la ville
                        select: function (event, ui) {
                            $('#edit-ville').val(ui.item.city);
                        }

                    });
                }
            });

1 Answer 1

1

You can push two values in autoCompleteData one will be label which we will be using in searching input field values and other any variable i.e : in below code i have use data: values[2] then we get this value and apply to your textbox using $('#edit-ville').val(ui.item.data);

Demo code :

$(document).ready(function() {
  var data = [
    "FR;24001;Périgueux",
    "FR;24002;Périgueux",
    "FR;24100;Saint-Laurent-des-Vignes",
    "FR;24100;Lembras",
    "FR;24100;Bergerac"
  ];
  //var autoCompleteData = data.split('\n');
  var lines = data;

  //Set up the data arrays
  var autoCompleteData = Array();

  for (var j = 0; j < lines.length; j++) {
    var values = lines[j].split(';'); // Split up the comma seperated values
    autoCompleteData.push({
      label: values[1],
      data: values[2] 
    });

  }

  //console.log(autoCompleteData[0][1]);
  $("#edit-code-postal").autocomplete({
    source: function(request, response) {
      var results = $.ui.autocomplete.filter(autoCompleteData, request.term);
      response(results.slice(0, 10)); // Display the first 10 results
    },
    // On remplit aussi la ville
    select: function(event, ui) {
      $('#edit-ville').val(ui.item.data);//setting value in textfield
    }

  });
});
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
</head>

<body>

  <div class="ui-widget">
    <label for="tags">Postal code (try "24...": </label>
    <input id="edit-code-postal">
    <label for="tags">City: </label>
    <input id="edit-ville">
  </div>


</body>

</html>

Sign up to request clarification or add additional context in comments.

2 Comments

Great. I am mostly a PHP developper and I don't exactly understand how ui.item.data works in $('#edit-ville').val(ui.item.data); Could you explain ?I think that was the issue for me.
autocomplete will take label and value to show result when you search , so if you don't provide this it will not display anything in your search textbox .In your current code you where using cp: values[1] which was not recognize by autocomplete. that's the reason it was not working .Also read this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.