jQuery-ui自动完成,选择第一项

时间:2017-03-15 15:45:54

标签: javascript jquery ruby-on-rails jquery-ui autocomplete

我在rails应用程序中使用jQuery-ui自动完成功能。当我输入一些输入时,我希望它自动选择自动完成框中的第一项。我该如何实现呢?

jQuery(function() {
    return $('#transaction_receiver_name').autocomplete({
        source: $('#transaction_receiver_name').data('autocomplete-source')
    });
});

我的css

.ui-helper-hidden-accessible {
  display: none;
}

ul.ui-autocomplete {
  position: absolute;
  list-style: none;
  margin: 0;
  padding: 0;
  border: solid 1px #999;
  cursor: default;
  li {
    background-color: #FFF;
    color: black;
    border-top: solid 1px #DDD;
    margin: 0;
    padding: 0;
    a {
      color: #000;
      display: block;
      padding: 3px;
    }
    a.ui-state-hover, a.ui-state-active {
      background-color: #FFFCB2;
    }
  }
}

Input field

2 个答案:

答案 0 :(得分:3)

您只需添加autoFocus: true,它就会自动选择列表中显示的第一个元素。

jQuery(function() {
    return $('#transaction_receiver_name').autocomplete({
        source: $('#transaction_receiver_name').data('autocomplete-source'),
        autoFocus: true
        }

    });
});

以下是一个例子:

$(function() {
  var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"
  ];
  $("#tags").autocomplete({
    source: availableTags,
    autoFocus: true,
    focus: function(event, ui) {
      event.preventDefault();
      //Here you can add anycode you want to be executed when an item of the box is selected
    },
    select: function(event, ui) {
      event.preventDefault();
     //Code here will be executed when an item is clicked on 
    }
  });
});
/* this will change the style of the selected element of the box*/

.ui-autocomplete .ui-menu-item .ui-state-active {
  color: blue;
  background: red;
}
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input id="tags">

答案 1 :(得分:1)

当菜单打开时,您可以收集第一个列表项并将其用作值。例如:

jQuery(function() {
  return $('#transaction_receiver_name').autocomplete({
    source: $('#transaction_receiver_name').data('autocomplete-source'),
    open: function(e, ui){
      var first = $(".ui-menu-item:eq(0) div").html();
      $(this).val(first);
      return false;
    }
  });
});

这是未经测试的。

另一种方法是触发点击第一个元素。

jQuery(function() {
  return $('#transaction_receiver_name').autocomplete({
    source: $('#transaction_receiver_name').data('autocomplete-source'),
    open: function(e, ui){
      $(".ui-menu-item:eq(0)").trigger("click");
      return false;
    }
  });
});