2012-01-17 83 views
1

我正在嘗試使用jQuery Ui自動完成來簡化HTML SELECT元素的行爲。jQuery UI自動完成:設置活動項目

是否可以在打開的事件上設置活動項目(移動焦點)?基本上,我試圖模仿HTML選擇元素中的selected =「selected」選項 - 如果字段中的值與列表中的值匹配,則使該列表項「選中」。

+0

什麼是你從這個例子裏缺了:http://jqueryui.com/demos/autocomplete/#combobox – Jere 2012-01-17 12:26:29

+0

當我從列表中選擇的東西,例如Clojure的 - 這樣的名單將被關閉,當我打開它再次,Clojure沒有被選中,它看起來完全像其他任何項目。 – ragulka 2012-01-17 18:10:17

回答

1

好了,我終於想通了,在朋友的幫助下答案。

$('input[data-field=vat_rate]', view.el).autocomplete({ 
    source: function (request, response) { 
     response(your_source_array); 
    }, 
    minLength: 0, 
    open: function (event, ui) { 
     var term = ui.item.value; 
     if (typeof term !== 'undefined') { 
      $(this).data("autocomplete").menu.activate(new $.Event("mouseover"), $('li[data-id=' + term + ']')); 
     } 
    } 
}).click(function() { 
    if ($(this).autocomplete('widget').is(':visible')) { 
     $(this).autocomplete('close'); 
    } else { 
     $(this).autocomplete('search'); 
    } 
}).data("autocomplete")._renderItem = function (ul, item) { 
    var listItem = $("<li></li>") 
     .data("item.autocomplete", item) 
     .attr("data-id", item.id) 
     .append('<a>' + item.label + '</a>') 
     .appendTo(ul); 
}; 

這裏的JSBin它:http://jsbin.com/unibod/2/edit#javascript

完美的作品! :)

1

這裏是什麼you'e尋找的jsfiddle:http://jsfiddle.net/fordlover49/NUWJr/

基本上,從jQuery的網站採取了combobox example,並改變了renderItem功能。在這個例子中關jqueryui.com的站點,改變的:

input.data("autocomplete")._renderItem = function(ul, item) { 
       return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.label + "</a>").appendTo(ul); 
    }; 

要:

input.data("autocomplete")._renderItem = function(ul, item) { 
     $item = $("<li></li>").data("item.autocomplete", item).append("<a>" + item.label + "</a>"); 
     if (this.element.val() === item.value) { 
      $item.addClass('ui-state-hover'); 
     } 

     return $item.appendTo(ul); 
    }; 
+0

嘿,謝謝,它幾乎是我想要的 - 除了當我用鍵盤打開列表並嘗試導航時,它從列表頂部開始,而不是從「活動」列表開始。不過,我已經找到了我要在這裏發佈的解決方案。 – ragulka 2012-01-30 07:17:48

1

您可以使用the focus event添加/刪除活動類。我比這個線程上的其他._renderItem代碼更喜歡它。

[...previous autocomplete options] 
focus: function(event, ui) { 
     // Remove the hover class from all results 
     $('li', ui.currentTarget).removeClass('ui-state-hover'); 

     // Add it back in for results 
     $('li',ui.currentTarget).filter(function(index, element) { 

     // Only where the element text is the same as the response item label 
     return $(element).text() === ui.item.label; 
    }).addClass('ui-state-hover'); 
}, 
[next autocomplete options...] 
+0

多數民衆贊成真棒@zack我只是腰了我的兩到三個小時,因爲我使用jQuery標籤編輯器自動完成插件創建自定義用戶界面。 – 2016-08-18 15:48:55