JQuery Autocomplete: Get the currently focused <li>
Asked Answered
G

2

7

JQuery Autocomplete triggers a focus event when the user mouses over or otherwise highlights one of its <li> options. Within this event, I want to refer to the <li> that is currently focused, but I can't figure out how to select it. At the moment, I have:

focus: function( event, ui ) {
  var target = event.currentTarget
  alert($(target).html())
}

But this returns the whole list of <li>s, rather than just the currently focused one. I've tried other event methods, such as event.delegateTarget and event.target, but with no success. Is there another way to get the focused element?

Glynas answered 1/2, 2013 at 21:52 Comment(3)
Please provide a jsfiddle exampleAstir
console.log(ui). it's in there.Hockenberry
@Ohgodwhy: No, it's not. That's the item being focused, not the li.Earvin
E
8

You're going to have to:

  1. Grab the menu widget that autocomplete is using.
  2. Get the li that's currently focused (this li has an a with class ui-state-focus

    focus: function (event, ui) {
        var menu = $(this).data("uiAutocomplete").menu.element,
        focused = menu.find("li:has(a.ui-state-focus)");
        // focused is the focused `li`
    }
    

Example: http://jsfiddle.net/J5rVP/43/

Earvin answered 1/2, 2013 at 22:9 Comment(0)
S
1

Are there any drawbacks when using the following instead?

focus: function(event, ui) {
    $(".ui-autocomplete li").removeClass("ui-state-hover");
    $(".ui-autocomplete").find("li:has(a.ui-state-focus)").addClass("ui-state-hover");
}
Suggest answered 2/3, 2013 at 9:25 Comment(2)
It's been awhile since I was dealing with this issue, but if I remember correctly, the problem with ui-state-focus was that it applied to the ul instead of the individuality focused li.Glynas
You really have the perfect solution. I was trying before solutions like applying .ui-state-focus and it doesn't work even after giving important in my case. Thanks a lot for the help.Swill

© 2022 - 2024 — McMap. All rights reserved.