自动完成所选值 - Jquery

Autocomplete selected value - Jquery

Jquery代码:

   var prefixes = [{
        "name": "Estonia",
        "dial_code": "+372",
        "code": "EE"
      }, {
        "name": "Latvia",
        "dial_code": "+371",
        "code": "LV"
      }, {
        "name": "Lithuania",
        "dial_code": "+370",
        "code": "LT"
      }, {
        "name": "Finland",
        "dial_code": "+358",
        "code": "FI"
      }, {
        "name": "Sweden",
        "dial_code": "+46",
        "code": "SE"
      }];

      prefixes = $.map(prefixes, function(item, i) {
        return {
          label: item.name + " " + item.dial_code,
          value: item.dial_code
        };
      });

          $('.js-phone-prefix input').autocomplete({
            delay: 0,
            minLength: 0,
            source: prefixes,
            appendTo: $('.js-phone-prefix')
          }).focus(function() {
            $(this).autocomplete('search', $(this).val())
          }).each(function() {
            $(this).autocomplete("widget").addClass("phone-prefix");
          });

HTML代码:

<div class="js-phone-prefix small" style="position: relative;">
  <input type="text" name="prefix" id="prefix" value="">
</div>

我正在尝试的是,当用户从列表中选择一个选项时,我想将该值设置为输入值。例如,如果用户选择 "Estonia",则输入值必须为 +372。有什么建议么? link to fiddle

$('.js-phone-prefix input').autocomplete({
    //...

    select: function( event, ui ){
        $(event.target).val(ui.item.value);
        console.log($('.ui-autocomplete-input').val());
    },

    //...

http://fiddle.jshell.net/6wc5r30h/2/

http://api.jqueryui.com/autocomplete/#event-select

根据 documentation,您必须在 select 自动完成选项时绑定一个事件。

$(".selector").autocomplete({
  select: function(e, ui) {
    // Code will be placed here
  }
});

因此在您的示例中,您必须将此添加到上面的代码中:ui.item.value 是您的值的对象)。

select: function(e, ui) {
  $(e.target).attr({'value' : ui.item.value});
}

请参阅JSFIDDLE更新