Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI autocomplete widget - how to get a reference to the menu?

Tags:

jquery-ui

I want to be able to get a reference to the menu object that autocomplete builds, (so I can get the .attr("id") for example), but I'm not very familiar with jQuery/javascript. In the source, I found this:

https://github.com/jquery/jquery-ui/blob/1-9-stable/ui/jquery.ui.autocomplete.js#L182

so there is an object flying around, I just can't seem to find how to get hold of it.

So, for example, if I've got an input with an autocomplete bound to it like this:

// input = reference to the input text box on the form
input.autocomplete({
  select: function(event, ui) {
    // how to get the reference here?

    // some things I've tried
    // return input.menu
    // return input.data("menu")
    // and a few others but they didn't work either
  }
});

I tried looking at the data object itself, but there were so many options I could spend all day looking at it and still not find what I'm looking for.

like image 426
ian Avatar asked Dec 21 '12 10:12

ian


2 Answers

You can get the widget's reference by looking into dataset assigned to its root element (input). Then fetching menu property (and its underlying element) is kinda trivial. )

  select: function(event, ui) {
    // that's how get the menu reference:
    var widget = $(this).data('ui-autocomplete'),
        menu   = widget.menu,
        $ul    = menu.element,
        id     = $ul.attr('id'); // or $ul[0].id
  }

... as this within select function refers to the <input> when this function called as an event handler.

like image 194
raina77ow Avatar answered Sep 18 '22 20:09

raina77ow


A simpler way to do this: $(this).autocomplete('widget');
It does the same as:

select: function(event, ui) {
// that's how get the menu reference:
var widget = $(this).data('ui-autocomplete'),
    menu   = widget.menu,
    $ul    = menu.element,
    id     = $ul.attr('id'); // or $ul[0].id

}

It gives the ul list

$(this).autocomplete('widget').attr('id');

like image 39
carloska Avatar answered Sep 21 '22 20:09

carloska