var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"];
$("#test").autocomplete({
minLength: 0,
source: availableTags,
autoFocus: true,
select: function (event, ui) {
if (ui.item) {
event.preventDefault();
$(this).val(ui.item.label);
}
},
open: function (event, ui) {
var menu = $(this).data("uiAutocomplete").menu;
var items = $('li', menu.element);
for (var i = 0; i < items.length; i++) {
if (items.eq(i).text().startsWith($(this).val())) {
menu.focus(null, items.eq(i));
break;
}
}
},
focus: function (event, ui) {
event.preventDefault();
if ($(this).val() == "" && !event.keyCode) {
//debugger;
$('.ui-menu-item a').removeClass('ui-state-focus');
}
else {
//$(this).data("uiAutocomplete").menu.element.children().first().focus();
}
}
}).on("focus", function () {
$(this).autocomplete("search", "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="test" class="col-md-3 col-lg-3 control-label"></label>
<div class="col-md-9 col-lg-7">
<input id="test" type="text" class="form-control" />
</div>
</div>
While tabbing through the page, inputs with autocomplete are filling out by default with the first option in dropdown. If I set minLength = 1
, problem solved. However, I have to keep minLength = 0
in order to pop up the dropdown when the input is focused.
One thought is that removing the focus class when first popping up the dropdown. But the problem is when I press the arrowdown, the second option is focused instead of the first one.
I cannot find any solution to manually focus the first option. Please help.
Any other solutions are more than welcome. Thanks in advance.