自动完成选择名称并在隐藏的输入中插入ID

时间:2019-05-13 09:12:06

标签: jquery json autocomplete

我知道有很多与此主题相关的答案,但是我花了一天的时间尝试使用它们来解决问题,但是我做不到,也许是因为我对JQuery和Autocomplete小部件不熟悉。 这是我使用的代码,它工作正常。问题是它插入了名称而不是ID。

这是JQuery脚本:

$.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);
    }
  });
});

这是HTML输入:

<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>

JSON文件内容:

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

1 个答案:

答案 0 :(得分:1)

尝试使用以下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>