Search code examples
javascriptfocus

JavaScript ui-autocomplete input doesn't focus


I have a problem with using focus() on an element which has ui-autocomplete

<input id="headerSearch" class="header-search-form-input form-control ui-autocomplete-input" name="query" type="text" value="" autocomplete="off">

and when I use $('#headerSearch').focus() to set cursor into a input field it doesn't work. I've read that it might be because this field already have event on it. I've checked it in Google Chrome EventListener and, yes, it has event.focus() on this field.

So my question is. How I can set focus and cursor on this field if it already have event on it? Thanks for helping.

UPD

I've found how to remove event from ui-component, but focus() it still doesn't work.

$('#headerSearch').off('focus'); 
$('#headerSearch,.header-search-form-label').focus();

Solution

  • When I click on a button the input will display (before it - hidden), maybe input for some time "not displayed" for the browser and it could not get focus because of it. So I did like that (it works):

    setTimeout(function() { $('#headerSearch').focus(); }, 100);
    

    Then I saw that I don't have to delete the event focus for this input. I think because I use method, not an event. But for some reason, many answers (when I try to find a solution) tell to delete the event if focus doesn't work for input.