Jquery .val()在ui-autocomplete select handler上没有改变任何东西

时间:2015-10-09 15:28:29

标签: javascript jquery jquery-ui

我有一个带有jquery-ui自动完成功能的输入。在自动完成“选择”功能上,我想将输入值更改为自动完成的所选项目。我必须这样做,因为我的数据结构不同于jquery-ui所期望的数据结构。一切正常,但是当我尝试设置输入值时没有任何变化,我也没有任何错误。

这是我的代码:

HTML:

<input type="text" placeholder="from" name="location" id="search-form-location" class="inputAddon-field flex-shrinker flex-grower" value="London, United Kingdom">

JS:

$( "#search-form-location" ).autocomplete({
  source: "/api/airports-autosuggest",
  minLength: 3,
  select: function( event, ui ) {
    console.log(JSON.stringify(ui.item,0,4));
    console.log($(this));
    $(this).val(ui.item.PlaceName);
  }
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
  if (item.PlaceId===item.CityId){
    return $( "<li>" )
    .append( "<span class='placeName'>"+ item.PlaceName +"</span> <span class='placeCode'>(All airports)</span> <span class='countryName'> " + item.CountryName +  "</span>" )
    .appendTo( ul );
  } else
  return $( "<li>" )
    .append( "<span class='placeName'>" + item.PlaceName + "</span> <span class='placeCode'>("+trump(item.PlaceId, "-sky" )+")</span> <span class='countryName'>" + item.CountryName + "</span> " )
    .appendTo( ul );
};

当我从autocomplete console.log(JSON.stringify(ui.item,0,4))中选择一个选项时,打印出我期望的对象(例如下面),console.log($(this))打印正确的对象,但输入字段变为空白并仅显示占位符。如果我在浏览器中检查它,我仍然会看到原始值attr:value =“London,United Kingdom”

ui.item对象:

 {
    "PlaceId": "LOND",
    "PlaceName": "London",
    "CountryId": "UK",
    "RegionId": "",
    "CityId": "LOND",
    "CountryName": "United Kingdom"
}

1 个答案:

答案 0 :(得分:1)

默认的select处理程序将覆盖您的自定义值。添加return false以防止事件处理逻辑传播到它:

select: function( event, ui ) {
    console.log(JSON.stringify(ui.item,0,4));
    console.log($(this));
    $(this).val(ui.item.PlaceName);
    return false;
  }

http://jqueryui.com/autocomplete/中的小提琴示例:http://jsfiddle.net/2qp708zo/