Is it possible to set the width of a jQuery autocomplete combobox?
Asked Answered
T

14

29

I am using this jQuery UI combobox autocomplete control out of the box off the jQuery UI website:

My issue is that I have multiple comboboxes on a page, and I want them to have different widths for each one.

I can change the width for ALL of them by adding this CSS:

 .ui-autocomplete-input
 {
     width: 300px;
 }

but I can't figure out a way to change the width on just one of them.

Thumping answered 22/4, 2010 at 6:31 Comment(2)
@oo but i can't figure out a way to change the width on just one of them which ones do you want to change css, every second, third, do you have any pattern to it? can you provide us with more info, more HTML or anything that would help you get the answerPlastic
Is it possible to wrap the comboxbox in a div or span. That way you can do a #foo .ui-autocomplete-input{ width:300px; }? Otherwise I agree with c0mrade.Nystatin
S
35

A simple

$('.ui-autocomplete-input').css('width','300px')

works (I tried it on the linked page with Firebug) to change the first one on the page.

You can do something like:

$($('.ui-autocomplete-input')[N]).css('width','300px') #N is the nth box on the page

To change the Nth one.

To find a specific one by a characteristic, you could do it in many ways.

Find it by the first "option" (in this example "asp"):

$('.ui-autocomplete-input').map(function(){if ($(this).parent().children()[1].options[0].text == 'asp'){ $(this).css('width','300px'); return false;} })

Find it by its "label":

$('.ui-autocomplete-input').map(function(){if ($($(this).parent().children()[0]).text() == "Your preferred programming language: "){ $(this).css('width','300px'); return false;}})

etc...

I'll update if you have an idea of how you want to find your combobox.

EDIT FOR COMMENT

oo, that makes it even easier. From the example source you linked to, the HTML is already wrapped in a div:

<div class="ui-widget" id="uniqueID">
    <label>Your preferred programming language: </label>
    <select>
        <option value="a">asp</option>
        <option value="c">c</option>
        <option value="cpp">c++</option>
        <option value="cf">coldfusion</option>
        <option value="g">groovy</option>
        <option value="h">haskell</option>
        <option value="j">java</option>
        <option value="js">javascript</option>
        <option value="p1">perl</option>
        <option value="p2">php</option>
        <option value="p3">python</option>
        <option value="r">ruby</option>
        <option value="s">scala</option>
    </select>
</div>

I would give that div a unique id then:

$('#uniqueID > input.ui-autocomplete-input').css('width', '300px')

That selects child elements of your div that are inputs with a class of "ui-autocomplete-input".

Sigh answered 24/4, 2010 at 19:9 Comment(2)
@Sigh - you are on the right track. I dont want to do it by index as it seems a bit flaky and hard to understand since its a random index and it may break if i add a new combobox. Lets say i put a div around each combobox. how could i select it based on the class name of the outer divThumping
@oo, see additions, using a uniquely ided outer div (actually using the one already in the linked example), makes it much, much simpler.Sigh
B
5

Note that I use the code in http://jqueryui.com/demos/autocomplete/#combobox.

In the _create method, add this line:

    _create: function() {
        var self = this;
        var eleCSS = this.element[0].className; //This line

Then scrolldown a little, find this:

    .addClass("ui-widget ui-widget-content ui-corner-left");

And change this to:

    .addClass("ui-widget ui-widget-content ui-corner-left "+ eleCSS);

HTML

<select class="combo-1 autocomplete">
    <option value="a">asp</option>
    <option value="c">c</option>
    <option value="cpp">c++</option>
    <option value="cf">coldfusion</option>
    <option value="g">groovy</option>
    <option value="h">haskell</option>
    <option value="j">java</option>
</select>

Now you can apply CSS to combo-1:

<script>
    $(function() {
        $('.autocomplete').combobox();
        $('.combo-1').css('width', '50px');
    });
</script>
Blurb answered 24/4, 2010 at 21:24 Comment(0)
B
5

Don't bother with JavaScript. You can easily do this in CSS as you were originally trying to do. All you need to do is add a unique selector to each one. For example:

HTML would look like this

<div class="title">
    <label for="title">Title: </label>
    <input id="title">
</div>
<div class="tags">
    <label for="tags">Tags: </label>
    <input id="tags">
</div>

CSS would look like this

.ui-autocomplete-input
{ 
    width: 120px;
}
.title .ui-autocomplete-input
{ 
    width: 200px;
}
.tags .ui-autocomplete-input
{ 
    width: 600px;
}
Bode answered 27/4, 2010 at 13:16 Comment(0)
A
5

JavaScript

var $myinput = $('#myinput').autocomplete({source: ['ABC', 'BCD', 'CDE']})
$myinput.data('autocomplete').menu.element.addClass('myautocomplete');

CSS

.myautocomplete{width:300px!important;}

You can't set the width directly, because it will get overwritten. But you can set the min-width directly.

var $myinput = $('#myinput').autocomplete({source: ['ABC', 'BCD', 'CDE']})
$myinput.data('autocomplete').menu.element.css('min-width', '300px');
Atc answered 20/1, 2012 at 10:12 Comment(0)
N
5

I use the following which is basicly one of the readily available widget init functions and might be what you are looking for too. I added just two simple lines to achieve it

$(function(){
$.widget( "ui.combobox", {
    _create: function() {
        var self = this,
        select = this.element.hide(),
        selected = select.children( ":selected" ),
        value = selected.val() ? selected.text() : "";
        var getwid = this.element.width(); // <<<<<<<<<<<< HERE
        var input = this.input = blah blah
        .insertAfter( select )
        .val( value )
        .autocomplete({
            delay: 0,
            minLength: 0,
            source: function( request, response ) {
                blah blah
            },
            blah blah
        })
        //?? .addClass( "ui-widget ui-widget-content ui-corner-left" );
        input.width(getwid); // <<<<<<<<<<<< AND HERE
        input.data( "autocomplete" )._renderItem = function( ul, item ) {
            blah blah

Note the lines var getwid etc and input.width(getwid);

This I worked out to copy the width of the select objects and apply it to the combo boxes as they (the autocomplete comboboxes) are created to overlay the select inputs.

Hope that helps. Regards.

PS: I believe that if you really just want to apply fixed widths not referencing the underlying select list then ignore the first line I added and change the second to compare a predefined array with the "this" id.

Nepheline answered 22/2, 2012 at 10:17 Comment(0)
B
3

I think the easiest way to do it is to capture the open event and then set the width there:

$("#autocompleteInput").bind("autocompleteopen", function(event, ui) {
  var width = 300;
  $(".ui-autocomplete.ui-menu").width(300);
});

Since only one autocomplete menu can be active at one time, it's okay to just change the width for the menu class.

Batho answered 10/11, 2010 at 18:1 Comment(0)
A
1

You could always set an actual CSS rule in your document to match the class,

.ui-autocomplete-input
{ 
    width: 300px;
}

if you know in advance how wide it has to be.

Alfi answered 24/4, 2010 at 19:13 Comment(2)
@Alfi - i tried that but, as mentioned, the issue with the above is that if affects all COMBOBOX autocomplete widths (instead of just one of them)Thumping
Point taken, but you can always be creative with the style rules, just add a container with an ID that you can match. Admittedly the jQuery selector rules are much more flexible and since you're already relying on it there is no harm in using it to do the css manipulation.Alfi
P
1
$.widget( "custom.myAutoComplete", $.ui.autocomplete, {
    options: {
        resultClass: "leanSolutions",
    },

    _create: function()
    {
        this._super();
    },`

    _renderMenu: function(ul, items)
    {
        var that = this;
        ul.addClass(that.options.resultClass);

        $.each( items, function( index, item ) {
            that._renderItemData( ul, item );
        });
    }
});

Now You Can do this:

$('.myAutoCompleteBox').myAutoComplete(
 data: ...
 etc: ...
 resultClass: 'myAutoCompleteBoxResultList'
);

And then you can style it

.myAutoCompleteBoxResultList{   
    width: 8000px;
}
Proportional answered 22/1, 2015 at 20:9 Comment(0)
C
1

It works for me using:

$.extend($.ui.autocomplete.prototype.options, {
  open: function(event, ui) {
    $(this).autocomplete("widget").css({
            "width": ($(this).outerWidth() + "px")
        });
    }
});

Thanks Michael Simons https://info.michael-simons.eu/2013/05/02/how-to-fix-jquery-uis-autocomplete-width/

Crafton answered 23/6, 2020 at 13:57 Comment(0)
T
0

Simply use the jQuery CSS method:

css("width", "300px");

http://api.jquery.com/css/#css2

You can append this after adding your combobox.

How do you use the combobox in your code?

Torgerson answered 22/4, 2010 at 12:35 Comment(3)
@Torgerson - dont quite follow. i use teh combobox exactly as it is listed on the above link. Given that, the main issue is that i dont have a specific ID selector for any of the specific input text that exist as the id of the dropdown combobox that you start off with is different than the input textbox itself. let me know if you dont followThumping
In the example $(function() {$("select").combobox();}); adds the combobox. So you have to add different classes to the select element, change your selector to select the different classes and append .css("width","300px");Torgerson
i think that will then break the other existing formatting that you would want to keep syncronized as the issue is the plugin itself seems like its creating these other elements inside of itself so you dont seem to have that level of control on a per input basis - maybe an example would clarify thingsThumping
S
0

With a small change to the jQuery UI code you can add a width to the .autocomplete() function.

If you are using the official jQuery UI autocomplete (I'm on 1.8.16) and would like to define the width manually.

If you're using the minified version (if not then find manually by matching _resizeMenu), find...

_resizeMenu:function(){var a = this.menu.element;a.outerWidth(Math.max(a.width("").outerWidth(), this.element.outerWidth()))}

...and replace it with (add this.options.width || before Math.max) ...

_resizeMenu:function(){var a = this.menu.element;a.outerWidth(this.options.width || Math.max(a.width("").outerWidth(), this.element.outerWidth()))}

You can now include a width value into the .autocomplete({width:200}) function and jQuery will honour it. If not, it will default to calculating it.

Sybille answered 15/9, 2011 at 13:49 Comment(0)
A
0

To have a full control on the autocomplete combobox and set the width automatically and give it an ID like "a_mycomboID"

change this line

input = $( "<input>" )

To

input = $( "<input id=a_"+select.attr('id')+" style='width:"+select.width()+"px;'>" )

This will automatically set the width, and will give it an ID such as a_[the id of the combo box]. This will allow you to control the behavior using the ID.

working example

Analgesic answered 26/9, 2012 at 9:45 Comment(0)
H
0
$input.data('ui-autocomplete')._resizeMenu = function () {
    var ul = this.menu.element;
    ul.outerWidth(this.element.outerWidth()); 
 }

If you doing inside your own widget, you can do something like

        // Fix width of the menu
        this.input = <your dom element where you bind autocomplete>;
        this.input.data("ui-autocomplete")._resizeMenu = function () {
            var ul = this.menu.element;
            ul.outerWidth(this.element.outerWidth())
        }
Hofmannsthal answered 26/4, 2016 at 10:45 Comment(0)
F
0

Set the max width instead of width, because width is override by plugin any time..

.ui-autocomplete-input
{ 
    max-width: 300px;/* you can set by percentage too */
}
Fizz answered 20/10, 2017 at 10:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.