I'm using jQuery UI's Autocomplete slightly differently than it was probably created to do.
Basically I want to keep all the same functionality, the only difference is that when the suggestion box appears, I don't the suggestion box to hide when a user makes a selection and I also don't want that selection to populate the input box that .autocomplete is attached to.
So, I've been reading through the jQuery UI documentation, and it appears there is a way to disable the Select: and Close: events, but I find the way they have explained it to be very confusing and hence, this is why I'm here asking for help.
My jQuery
$( "#comment" ).autocomplete({
source: "comments.php",
minLength: 4,
// Attempt to remove click/select functionality - may be a better way to do this
select: function( event, ui ) {
return false;
},
// Attempt to add custom Class to the open Suggestion box - may be a better way
open : function (event, ui) {
$(this).addClass("suggestion-box");
},
// Attempt to cancel the Close event, so when someone makes a selection, the box does not close
close : function (event, ui) {
return false;
}
});
Official jQuery UI documentation
Triggered when an item is selected from the menu; ui.item refers to the selected item. The default action of select is to replace the text field's value with the value of the selected item. Canceling this event prevents the value from being updated, but does not prevent the menu from closing.
Code examples
Supply a callback function to handle the select event as an init option.
$( ".selector" ).autocomplete({
select: function(event, ui) { ... }
});
Bind to the select event by type: autocompleteselect.
$( ".selector" ).bind( "autocompleteselect", function(event, ui) {
...
});
Confusion
What confuses me is that they seem to be suggesting to remove the .autocomplete and replace with .bind("autocompleteselect") - which will disable the autocomplete altogether?
Thank you very much for any help you can give.
Taking inspiration from Andrews solution, I found a way to keep autocomplete open on selection with less impact on core functionality:
var selected; //flag indicating a selection has taken place
var $input = $("input").autocomplete({
source: ['Hello', 'Goodbye', 'Foo', 'Bar'],
select: function( event, ui ) {
selected = true;
}
});
//Override close method - see link below for details
(function(){
var originalCloseMethod = $input.data("autocomplete").close;
$input.data("autocomplete").close = function(event) {
if (!selected){
//close requested by someone else, let it pass
originalCloseMethod.apply( this, arguments );
}
selected = false;
};
})();
So the idea is to neuter close method when appropriate, as indicated by selected flag. Having selected flag in global name space probably isn't the best idea, but that's for someone else to improve on :-).
More about overriding methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With