当使用
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> </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);