如何使用 jquery 自动完成组合框设置默认值?

发布于 2024-08-30 14:44:14 字数 153 浏览 6 评论 0原文

使用jquery ui autocomplete combobox时,可以设置默认值吗组合框的值?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

左秋 2024-09-06 14:44:14

我尝试以我自己的项目中的方式回答这个问题。

我从您发布的页面上阅读了演示源代码。在生成自动完成组合框的 jquery 代码中,我添加了一行代码,该代码在创建组合框时进行处理,从“select”元素中读取所选值。通过这种方式,您可以通过编程方式设置默认值(就像您通常不使用自动完成组合框一样)

这是我添加的一行:

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

简单明了。它将输入值设置为 #combobox 中所选元素的文本值。当然,您会想要更新 id 元素以匹配您的个人项目或页面。

这是在上下文中:

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

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> </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);
祁梦 2024-09-06 14:44:14

基于Mathieu Steele 答案,而不是使用这个:

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

我使用这个:

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

Widget 现在是可重用的并且是 DRY :)

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 :)

小巷里的女流氓 2024-09-06 14:44:14

答案#1 非常接近,但如果您想保持函数通用,则不能对元素 ID 进行硬编码。添加此行即可享受!

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

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() );
彻夜缠绵 2024-09-06 14:44:14

您可以通过编辑自动完成器的以下语句来实现此目的:

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

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

value = selected.val() ? selected.text() : "Select Institution";
挽手叙旧 2024-09-06 14:44:14

我已经调整了此处的响应,以使用组合框已定义的选择变量来查找所选选项并使用它。这意味着它对于您在其上定义组合框的任何元素(使用 id、class 或选择器)都是通用的,并且也适用于多个元素。

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

希望这对某人有帮助!

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!

ゃ人海孤独症 2024-09-06 14:44:14

将方法添加到 jquery 组合框脚本

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

add method to jquery combobox script

setValue: function(o) {            
    $(this.element).val(o);
    $(this.input).val($(this.element).find("option:selected").text());            
}
離人涙 2024-09-06 14:44:14

初始化后,调用 option 方法来设置框的值。

$('#combo').autocomplete( "option" , optionName , [value] )

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

$('#combo').autocomplete( "option" , optionName , [value] )
不…忘初心 2024-09-06 14:44:14
input.val( $(select).children("option:selected").text());
input.val( $(select).children("option:selected").text());
哆兒滾 2024-09-06 14:44:14

我使用下面的代码行,只是实现相同结果的另一种方法:)

$('option:selected', this.element).text()

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

$('option:selected', this.element).text()
來不及說愛妳 2024-09-06 14:44:14

我有一个适用于我的 jquery UI 组合框实现的答案。代码中间的某个地方是这样的:

.val(value)

我将其更改为:

.val(select.val())

很快,底层文本框的初始值出现了。在我看来这应该是默认功能,但我知道什么?

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?

岛徒 2024-09-06 14:44:14

在“ this._on( this.input, { ” 行之前添加以下一行代码

this.input[0].defaultValue = value;

在自动完成组合框脚本中创建代码后, 。
您还可以使用 html 的重置按钮进行重置。

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.

亣腦蒛氧 2024-09-06 14:44:14

我遇到了这个错误,无论我编码什么,都无法修复它的 OnLoad 事件(可能需要 3 小时)。最后幸运的是我遇到了 http://www .onemoretake.com/2011/04/17/a-better-jquery-ui-combo-box/ 网页(感谢@Dan解决了我的头痛问题)并看到真正缺失的部分不在“OnLoad”上”,关于 ui 定义函数本身。官方 Jquery Ui 网页上的标准定义函数不包含以编程方式选择选项。

这是应该添加到定义函数中的函数:

//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;
                }
            });
        }

我还生成了另一个函数来通过选项文本而不是选项值更改选择

//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;
                    }
                });                        
            }

您可以在 OnLoad 或另一个函数上使用这些函数,如下所示:

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

$("#yourComboBoxID").combobox("setValueText", "Your Option Text");

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");
七婞 2024-09-06 14:44:14
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());
}

我通过在初始页面或运行时调用此函数解决了这个问题。例子:

setAutoCompleteCombo('#frmData select#select_id',option_value,option_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());
}

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

setAutoCompleteCombo('#frmData select#select_id',option_value,option_text);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文