Reputation: 19425
I have an autocomplete input field that is hidden until I click an item. In order to avoid having the user to click the inputbox, I want to use .focus()
.
Using this alone works. The probloem is that when I start typing, the autocomplete is not working. So I have to trigger the autocompelte functions. The functions I use is this:
self.find('.search-city').on('focus', function(){
$(this).acCity(); // Custom function for autocomplete
});
The problem is that as soon as I use function()
it loses focus. You can see the fiddle here.
How can this be resolved?
Upvotes: 0
Views: 57
Reputation: 93571
You are registering a focus event handler instead of calling focus()
which sets focus on the element.
Assuming you want both it would be more like this http://jsfiddle.net/TrueBlueAussie/totgn883/3:
$('.container').on('click', function(){
var self = $(this);
self.find('.city').hide();
self.find('.input-wrapper').addClass('show');
self.find('.search-city').focus(); // Works fine
});
// Listen for a focus event - does not cause focus to occur
$('.search-city').focus( function(){
// Does not work
console.log("I am focused");
});
Note: Going by the comment below you seem to think $('.search-city').focus( function(){
fires a focus event. It does not. It registers a function to be called when the element actually gets focused.
Upvotes: 2
Reputation: 193271
Because when you use callback function syntax:
.focus(function () {
// Does not work
});
you bind an event, not fire it.
In you case you should simply trigger focus event with a call .focus()
(or .trigger('focus')
).
Upvotes: 1