How do you set a default value with jquery auto complete combobox?
Asked Answered
W

14

17

When using the jquery ui autocomplete combobox, can you set a default value for the combobox?

Weather answered 1/5, 2010 at 11:24 Comment(0)
A
24

I tried answer this in the way that I would do it in my own project.

I read through the demo source code from the page you posted. In the jquery code that generates the autocomplete combobox, I added one line of code that processes when the combobox is created that reads the selected value from your "select" element. This way you can programmatically set the default value (like you would normally if you were not using the autocomplete combobox)

Here is the one line I added:

input.val( $("#combobox option:selected").text());

Plain and simple. It sets the value of input to the text value of the selected element from #combobox. Naturally, you will want to update the id elements to match your individual project or page.

Here it is in context:

(function($) {
    $.widget("ui.combobox", {
        _create: function() {
            var self = this;
            var select = this.element.hide();
            var input = $("<input>")
                .insertAfter(select)
                .autocomplete({
                    source: function(request, response) {
                        var matcher = new RegExp(request.term, "i");
                        response(select.children("option").map(function() {
                            var text = $(this).text();
                            if (this.value && (!request.term || matcher.test(text)))
                                return {
                                    id: this.value,
                                    label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
                                    value: text
                                };
                        }));
                    },
                    delay: 0,
                    change: function(event, ui) {
                        if (!ui.item) {
                            // remove invalid value, as it didn't match anything
                            $(this).val("");
                            return false;
                        }
                        select.val(ui.item.id);
                        self._trigger("selected", event, {
                            item: select.find("[value='" + ui.item.id + "']")
                        });

                    },
                    minLength: 0
                })
                .addClass("ui-widget ui-widget-content ui-corner-left");



            // This line added to set default value of the combobox
            input.val( $("#combobox option:selected").text());





            $("<button>&nbsp;</button>")
            .attr("tabIndex", -1)
            .attr("title", "Show All Items")
            .insertAfter(input)
            .button({
                icons: {
                    primary: "ui-icon-triangle-1-s"
                },
                text: false
            }).removeClass("ui-corner-all")
            .addClass("ui-corner-right ui-button-icon")
            .click(function() {
                // close if already visible
                if (input.autocomplete("widget").is(":visible")) {
                    input.autocomplete("close");
                    return;
                }
                // pass empty string as value to search for, displaying all results
                input.autocomplete("search", "");
                input.focus();
            });
        }
    });

})(jQuery);
Abloom answered 11/5, 2010 at 0:53 Comment(1)
Is there any way in which I can have a default value other than the ones present in the created unordered list?Perishing
H
19

Based on Mathieu Steele answer, instead of using this:

input.val( $("#combobox option:selected").text());

I use this:

input.val( $(select).find("option:selected").text());

Widget is now reusable and DRY :)

Heathenize answered 11/8, 2010 at 19:36 Comment(0)
W
2

Answer #1 is very close, but you cannot hard-code the element ID if you want to keep the function generic. Add this line instead and enjoy!

input.val(jQuery("#"+select.attr("id")+" :selected").text() );
Wariness answered 19/5, 2010 at 4:5 Comment(0)
B
2

You can achieve this by editing the following statement of the auto-completer:

value = selected.val() ? selected.text() : "Select Institution";
Blowgun answered 19/1, 2012 at 10:47 Comment(0)
D
1

I've tweaked the responses here to use the select variable already defined by the combobox to find the selected option and use that. This means it is generic for which ever element you have defined the combobox on (using id, class or selector ) and will work for multiple elements also.

input.val(select.find("option:selected").text());

Hope this helps someone!

Density answered 1/7, 2010 at 14:30 Comment(0)
B
1

add method to jquery combobox script

setValue: function(o) {            
    $(this.element).val(o);
    $(this.input).val($(this.element).find("option:selected").text());            
}
Barham answered 20/12, 2011 at 11:52 Comment(0)
B
0

Call the option method to set the box's value after you've initialized it.

$('#combo').autocomplete( "option" , optionName , [value] )
Bywaters answered 4/5, 2010 at 4:17 Comment(2)
this doesn't seem to do anything in the combobox example.Weather
This is incorrect. The available options (for optionName) are disabled, appendTo, autoFocus, delay, minLength, position and source. None of these options set the initial value.Gigantopithecus
S
0

may be this will help you

http://forum.jquery.com/topic/autocomplete-default-value

Steric answered 9/5, 2010 at 22:45 Comment(1)
for some reason just doing ("#selector").val(value) doesn't seem to do anything for the combobox example.Weather
A
0
input.val( $(select).children("option:selected").text());
Allie answered 19/7, 2010 at 19:46 Comment(0)
C
0

I used the below line of code instead, just another way of achieving the same result :)

$('option:selected', this.element).text()
Critique answered 13/3, 2012 at 6:17 Comment(0)
F
0

I have an answer that worked for my implementation of the jquery UI combobox. Somewhere in the middle of the code was this:

.val(value)

I changed it to:

.val(select.val())

and presto, the initial value of the underlying textbox appeared. Seems to me like this should be the default functionality, but what do I know?

Femme answered 14/4, 2013 at 0:42 Comment(0)
P
0

Add below One Line of Code before " this._on( this.input, { " line

this.input[0].defaultValue = value;

after create code in autocomplete combobox script. You can also reset with reset button of html.

Peltate answered 21/1, 2014 at 5:40 Comment(0)
A
0

I stumped this error and cannot fix it OnLoad event whatever I coded (Probably on 3 hours). At last luckily I acrossed http://www.onemoretake.com/2011/04/17/a-better-jquery-ui-combo-box/ web page(Thx for @Dan for solving my headache) and saw the real missing part is not on "OnLoad", on ui definition function itself. Standart definition function on the official Jquery Ui web page does not contain programmatically select option.

Here is the function should added to definition function :

//allows programmatic selection of combo using the option value
        setValue: function (value) {
            var $input = this.input;
            $("option", this.element).each(function () {
                if ($(this).val() == value) {
                    this.selected = true;
                    $input.val(this.text);
                    return false;
                }
            });
        }

also i produced another function to change selection via option text not option value

//allows programmatic selection of combo using the option text
            setValueText: function (valueText) {
                var $input = this.input;
                var selectedText;                   
                $("option", this.element).each(function () {
                    if ($(this).text() == valueText) {
                        this.selected = true;
                        $input.val(this.text);                                                    
                        return false;
                    }
                });                        
            }

You can use these functions on OnLoad or another function as :

$("#yourComboBoxID").combobox("setValue", "Your Option Value");

or

$("#yourComboBoxID").combobox("setValueText", "Your Option Text");
Anamariaanamnesis answered 4/4, 2015 at 12:39 Comment(0)
F
-1
function setAutoCompleteCombo(id,value,display) {
    if($(id+"[value="+value+"]").text().localeCompare("")==0){
        $("<option value='"+value+"'>"+display+"</option>").appendTo($(id));
    }
    $(id).val(value);
    $(id).next().val($(id+" :selected").text());
}

I solved it by calling this function on the initial page or runtime. Example:

setAutoCompleteCombo('#frmData select#select_id',option_value,option_text);
Fuchsia answered 4/5, 2010 at 4:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.