Pregunta

Cuando se utiliza el jQuery UI autocompletar cuadro combinado , que puede establecer un valor predeterminado para el cuadro combinado?

¿Fue útil?

Solución

He intentado responder a esta en la forma en que lo haría en mi propio proyecto.

He leído a través del código fuente de demostración desde la página informados. En el código de jQuery que genera el desplegable de autocompletar, he añadido una línea de código que los procesos cuando se crea el cuadro combinado que se lee el valor seleccionado de su elemento de "seleccionar". De esta manera se puede establecer mediante programación el valor por defecto (como lo haría normalmente si usted no estaba usando el desplegable de autocompletar)

Esta es la una línea añadí:

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

Así de simple. Se establece el valor de entrada para el valor de texto del elemento seleccionado de #combobox. Naturalmente, tendrá que actualizar los elementos de identificación para que coincida con su proyecto individual o de página.

Aquí está en contexto:

(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);

Otros consejos

Basado en Mathieu Steele respuesta , en lugar de utilizar esto:

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

Yo uso este:

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

Widget es ahora reutilizable y seco:)

La respuesta # 1 está muy cerca, pero no se puede difícil que el código de identificación del elemento si desea mantener la función genérica. Añadir esta línea en su lugar y disfrutar!

input.val(jQuery("#"+select.attr("id")+" :selected").text() );

Se puede lograr esto mediante la edición de la siguiente declaración de la auto-más completa:

value = selected.val() ? selected.text() : "Select Institution";

he ajustado las respuestas aquí para utilizar el selecto variables ya definidas por el cuadro combinado para encontrar la opción seleccionada y usar eso. Esto significa que es genérico para el que jamás elemento que haya definido en el cuadro combinado (mediante la identificación, la clase o el selector) y trabajará para múltiples elementos también.

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

Espero que esto ayude a alguien!

método de añadir a la escritura jQuery cuadro combinado

setValue: function(o) {            
    $(this.element).val(o);
    $(this.input).val($(this.element).find("option:selected").text());            
}

Llame al método option para fijar el valor de la caja después de haber inicializado.

$('#combo').autocomplete( "option" , optionName , [value] )
input.val( $(select).children("option:selected").text());

He utilizado el siguiente línea de código en su lugar, sólo otra manera de lograr el mismo resultado:)

$('option:selected', this.element).text()
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());
}

Lo resuelto por llamar a esta función en la página inicial o en tiempo de ejecución. Ejemplo:

setAutoCompleteCombo('#frmData select#select_id',option_value,option_text);

tengo una respuesta que trabajó para mi aplicación de la lista desplegable jQuery UI. En algún lugar en medio del código era la siguiente:

.val(value)

He cambiado a:

.val(select.val())

y listo, el valor inicial de la caja de texto subyacente apareció. Me parece que esta debe ser la funcionalidad por defecto, pero ¿qué sé yo?

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.

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");
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top