Reputation: 3488
I tried to prevent jquery autocomplete from closing the search result if I click outside of the search result box, if the input is not empty and if the result is > 0. That's my fiddle:
It already stays open when clicking outside the search result box, but also if I clear the input which I obviously don't want. There is already a similar question: JqueryUI Autocomplete prevent close on click outside
E.g. the .dialog() function has sth like clickOutside: false
That's my setup:
html:
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
<button id="clear-search" >Clear</button>
</div>
javascript:
$(function () {
$("#tags").autocomplete({
source: availableTags,
delay: 0,
close:function(event, ui){
if ( $('.ui-autocomplete > li').length > 0 ) {
$("ul.ui-autocomplete, .ui-widget-content").filter(':hidden').show();
} else {
// I tried this:
$('#tags').autocomplete( 'close' );
$('ul.ui-autocomplete').remove();
$('ul.ui-autocomplete').hide();
}
}
});
});
$('#clear-search').on('click', function() {
$('#tags').val('');
});
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"];
Upvotes: 2
Views: 2179
Reputation: 10869
Perhaps not the most elegant solution, but I think it does what you wanted - just checks the length of the input, and if 0 calls close
.
Adding as an answer as it is too long for a comment:
$(function() {
$("#tags").autocomplete({
source: availableTags,
delay: 0,
close: function(event, ui) {
var input_length = $('#tags').val().length;
if (input_length !== 0) {
console.log(input_length);
$("ul.ui-autocomplete, .ui-widget-content").filter(':hidden').show();
} else if (input_length === 0) {
console.log("its 0 now!");
$('#tags').autocomplete('close');
}
}
});
});
$('#clear-search').on('click', function() {
$('#tags').val('');
});
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
Upvotes: 5