jqueryjquery-uiautocompletejquery-ui-autocomplete

jQuery UI Autocomplete Width Not Set Correctly


I have implemented a jQuery UI Autocomplete box, and rather than being the width of the textbox, the dropdown options are expanding to fill the remaining width of the page.

Have a look at this example to see it for yourself: http://jsbin.com/ojoxa4

I have tried setting the width of the list immediately after creating it, like so:

$('.ui-autocomplete:last').css('width',
                               $('#currentControlID').width()
                              );

This appears to do nothing.

I have also tried setting the width using on-page styles:

ui-autocomplete { width: 500px; }

This DOES work, amazingly, however it would mean that all autocompletes on a page would have to be the same width, which is not ideal.

Is there a way to set the width of each menu individually? Or better, can anyone explain why the widths are not working correctly for me?


Solution

  • It turns out the problem is that the menu is expanding to fill the width of its parent element, which by default is the body. This can be corrected by giving it a containing element of the correct width.

    First I added a <div> like so:

    <div id="menu-container" style="position:absolute; width: 500px;"></div>
    

    The absolute positioning allows me to place the <div> immediately after the input without interrupting the document flow.

    Then, when I invoke the autocomplete, I specify an appendTo argument in the options, causing the menu to be appended to my <div>, and thus inherit its width:

    $('#myInput').autocomplete({ source: {...}, appendTo: '#menu-container'});
    

    This fixes the problem. However, I'd still be interested to know why this is necessary, rather than the plug-in working correctly.