Reputation: 2677
What is the easiest way to trigger select
event on jQuery UI Autocomplete search field when browsing results with arrow keys up and down? After that user can clear the field by pressing backspace only once.
You can test your approach with this jsfiddle copied from here.
Upvotes: 0
Views: 314
Reputation: 30883
Taking a note from this Demo: https://jqueryui.com/autocomplete/#multiple
You can do something like this:
https://jsfiddle.net/Twisty/7m9qs3wc/5/
JavaScript
function quickDel(tObj) {
tObj.val("");
}
$("#tags").on("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.BACKSPACE &&
!$(this).autocomplete("instance").menu.active) {
event.preventDefault();
quickDel($(this));
}
}).autocomplete({
source: availableTags
});
This will quickly delete all the content of the field when Backspace is the Menu is NOT active.
If you want to highlight it, you can write a highlight function to be used in focus
and trigger it in Select
callback.
Example: https://jsfiddle.net/Twisty/7m9qs3wc/12/
Note, focus
in Autocomplete is in regards to the Menu items. So we call .on("focus")
for the field itself.
Or do it all when you have Focus on a menu item: https://jsfiddle.net/Twisty/7m9qs3wc/19/
Upvotes: 0
Reputation: 815
You get to a point where you're competing with jQueryUI for focus, but you can get around this by setting a timeout, so your focus takes place on the next js cycle after jQueryUI is done.
You can use AutoComplete's focus event:
$( "#tags" ).autocomplete({
source: availableTags,
focus: optionFocused
});
And then build a function that selects and focuses the text on the next cycle
function optionFocused(event, ui) {
setTimeout(function(){
$('#tags').select().focus();
}, 0)
}
Here's a working snippet
function optionFocused(event, ui) {
setTimeout(function(){
$ ('#tags').select().focus();
}, 0)
}
$(document).ready(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,
focus: optionFocused
});
});
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"
integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E="
crossorigin="anonymous"></script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
Upvotes: 1