I understand there are many answers related to this topic, however I tried for one day to solve my problem using them, but I couldn't, maybe because I am not familiar with JQuery and Autocomplete widget. Here is the code I use, it works fine. The problem is it, it inserts the name not the id.

Here is JQuery script:

$.getJSON('file.json', function(data){
  var autoComplete = [];
  for (var i = 0, len = data.length; i < len; i++) {
    autoComplete.push(data[i].name);
  }
  $('#user').autocomplete({
    source: autoComplete,
    minLength: 2,
    select: function(event, ui) {
      $('#id').val(ui.item.value);
    }
  });
});

This is HTML inputs:

<div class="ui-widget">
  <label for="user">User: </label>
  <input id="user">
</div>
<div class="ui-widget">
  <label for="id">ID: </label>
  <input id="id">
</div>

The JSON file content:

[
  {"name":"John","id":"111"},
  {"name":"Robert","id":"222"},
  {"name":"Sozi","id":"333"}
]

1 Answers

1
user3604331 On Best Solutions

Try with below jQuery:

<script>
     $(function() {
     //Create array
        var array = {};
        $.getJSON('file.json', function(data){
        var autoComplete = [];
        for (var i = 0, len = data.length; i < len; i++) {
            autoComplete.push(data[i].name);
            //pass the id as value and key as name in array
            array[data[i].name] = data[i].id;
        }

        $('#user').autocomplete({
            source: autoComplete,
            minLength: 2,
            select: function(event, ui) {
            //get the value based on name from the array and put in input field
            $('#id').val(array[ui.item.value]);
            }
        });
        });
    });
  </script>

    <div class="ui-widget">
        <label for="user">User: </label>
        <input id="user">
    </div>
    <div class="ui-widget">
        <label for="id">ID: </label>
        <input id="id">
    </div>