![](/img/trans.png)
[英]How to select coordinates from GeoJSON via jQuery-UI autocomplete?
[英]jQuery-ui autocomplete, select first item
我在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;
}
}
}
您只需要添加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">
菜單打開時,您可以收集第一個列表項並將其用作值。 例如:
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;
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.