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?
I use this drop-in solution:
jQuery.ui.autocomplete.prototype._resizeMenu = function () {
var ul = this.menu.element;
ul.outerWidth(this.element.outerWidth());
}
That's basically @madcapnmckay's solution, but that doesn't need to change the original source.
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.
I know this has long since been answered, but i think there is a better solution
$(".autocomplete").autocomplete({
...
open: function() {
$("ul.ui-menu").width( $(this).innerWidth() );
...
}
...
});
It worked fine for me.
I had a dig around in the autocomplete code and the culprit is this little blighter
_resizeMenu: function() {
var ul = this.menu.element;
ul.outerWidth( Math.max(
ul.width( "" ).outerWidth(),
this.element.outerWidth()
) );
},
I'm not sure what ul.width("") is suppose to be doing but ui.width("").outWidth() always returns the width of the body because that's what the ul is appended to. Hence the width is never set to the elements width....
Anyway. To fix simply add this to your code
$element.data("autocomplete")._resizeMenu = function () {
var ul = this.menu.element;
ul.outerWidth(this.element.outerWidth());
}
Is this a bug?
EDIT: In case anyone wants to see a reduced test case for the bug here it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With