jQuery自动完成在外部点击时选择第一个数据?

时间:2014-04-19 07:28:55

标签: jquery jquery-ui-autocomplete

我正在使用Jquery + JS + rails4

    function get_city_names(div_name, div_id, cities){
  div_name = "#" + div_name;
  div_id = "#" + div_id;
     $(div_name).autocomplete({
        autoFocus: true,
        maxLength: 5,
        source:  function(request, response) {
          var matcher = new RegExp( "^" +   $.ui.autocomplete.escapeRegex( request.term ), "i" );
          response( $.grep(cities, function( item ){
              return matcher.test(item.name);
          }) );
      },
      // Focus - if you mouse over any item the input field replace by that value
        // focus: function( event, ui ) {
        //   console.log(ui.item.name);
        //   $(div_name).val( ui.item.name );
        //   return false;
        // },
        // Select - If you  select any item it'll give the values (ID) and label
        select: function(event, ui) {
          $(div_name).val(ui.item.name); // Label display
          $(div_id).val(ui.item.id); // Assign ID with respect city.
          return false;
        },
        // close: function(event, ui) {
        //   $(div_name).autocomplete('close');
        // },
      }).data( "ui-autocomplete" )._renderItem = function(ul, item) {
      console.log(ul[0]);
        return $("<li>")
          .append( "<a>" + item.name + "</a>" )
          .appendTo(ul);
      };
}

自动完成工作正常,但我希望当我点击外面然后它应该从列表中自动获取第一个。

任何建议?

1 个答案:

答案 0 :(得分:0)

使用focus out事件并检查此select first的扩展名。希望它有所帮助..