jQuery autocomplete mouse choice fires the blur event
I use the jQuery UI .autocomplete()
, which I really love. I 开发者_如何学Cdo have one major problem I cannot solve.
When I type a letter, say s, and stackoverflow appears in the drop-down menu, and I use the mouse to select stackoverflow, then the input box temporarily loses focus, which causes the onblur
event to be called.
Although technically the input box is blur
ed when I click, this goes against usability intuition. How can I fix this annoying behavior?
you can try using the jQuery UI autocomplete's open and close event to control your textbox's blur event. When the autocomplete is open you disable the blur event and when it close you enable your blur event again. I have setup a working example at jsfiddle.net. Hope it helps.
var disable=false;
$( "#tags" ).autocomplete({
source: availableTags,
open: function(event, ui) { disable=true },
close: function(event, ui) {
disable=false; $(this).focus();
}
}).blur(function() {
if(!disable) {
alert('blur');
}
});
what do you have in your blur event? It's kind of hacky but you could do a setTimeout with a relatively short delay for your blur's handler. Then you can set a variable in the autocomplete's focus event handler and tell your blur handler to not fire.
While drzone88's answer above works great, there is one edge case that I stumbled on which should be brought up: when you search and have no results displayed, the close event is never called. Then your blur function will also never be called. So I settled with setting the flag when response content is empty.
My solution also uses jquery.data() so we don't have to drag a variable around:
$( ".selector" ).autocomplete({
source: ["your values here"],
open: function(event, ui) { $(this).data("no-blur", true); },
close: function(event, ui) {
$(this).data("no-blur", false);
},
response: function(event, ui){
if(ui.content.length == 0) //when search results are empty, close is not called
$(this).data("no-blur", false);
else
$(this).data("no-blur", true); //not sure open is called again either if we re-get results
}
}).on("blur", function() {
if(!$(this).data("no-blur")) {
//do something
}
});
As it turns out, though, because of the order in which events are called and what I actually needed to do (fire something on blur when user blurs the field without selecting an option in the suggestion list), I ended up setting my noblur flag to true at the start of the select function, and back to false at the end of the blur, like so:
$( ".selector" ).autocomplete({
source: ["your values here"],
select: function(ui, event){
$(this).data("no-blur", true);
//do select stuff
},
}).on("blur", function() {
if(!$(this).data("no-blur")) {
//do something
}
$(this).data("no-blur", false);
});
Hope this can help someone!
精彩评论