自动填充选定的值 - Jquery

时间:2015-08-31 13:08:06

标签: jquery jquery-autocomplete jquery-ui-autocomplete

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>

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

2 个答案:

答案 0 :(得分:1)

$('.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

答案 1 :(得分:1)

根据documentation,您必须在自动填充选择选项时绑定事件。

$(".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已更新