gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:53:13 25 4
gpt4 key购买 nike

当使用the jquery ui autocomplete组合框,可以为组合框设置默认值吗?

最佳答案

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

我阅读了您发布的页面上的演示源代码。在生成自动完成组合框的 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>&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);

关于jquery - 如何使用 jquery 自动完成组合框设置默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2749721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com