2012-02-04 82 views
1

首先,對這個問題的標題感到抱歉。我想了很長一段時間,並沒有更好的辦法。關於一個字段下的多個值的建議 - jQueryUI自動完成

我的問題是:jQueryUI的自動完成功能可以在一個自動填充字段下提供來自多個數據庫字段的建議。例如,我希望能夠在字段中輸入「br」,並且「briman057」和「Brian Johnson」作爲建議出現,即使它們存儲在單獨的數據庫字段中並作爲兩個單獨的鍵值返回對相同的JSON項目(即[{用戶名:briman057,名稱:'Brian Johnson'}})。然後,我希望用戶名的值是填充該字段的時候,或者全名被選中。我知道其中一個鍵需要命名爲「value」或「label」,並且該名稱的鍵是用於提供建議的鍵,但是對於一個JSON項目,我基本上可以擁有兩個「值」鍵嗎?

回答

0

是的,它可以,因爲您提供自己的自定義回調作爲數據源。該回調可以實現你想要的行爲。

下面是我認爲你想要的一個演示。

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script> 
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" /> 
<script type="text/javascript"> 
$(function() { 
    $('#myautocomplete').autocomplete({ 
    source: function(request, response) { 
     // TODO: make suggestions actually depend on what the user types into the search box. 

     // You want two suggestions, one with 'briman57' and one with 'Brian Johnson', so we need two suggestions with different labels, but with the same value. 
     var suggestions = [ 
     { label: 'briman057' , value: 'briman057', username : 'briman057', name : 'Brian Johnson'}, 
     { label: 'Brian Johnson', value: 'briman057', username : 'briman057', name : 'Brian Johnson'} 
     ]; 
     response(suggestions); 
    }, 
    select: function(event, ui) { 
     alert('You have selected ' + ui.item.name + ' (' + ui.item.username + ')'); 
    } 
    }); 
}); 
</script> 
<input id="myautocomplete" title="Enter anything here."></input> 

看看Remote JSONP datasource example的源代碼獲取更多靈感。

+0

感謝您添加編輯。我看了一下鏈接,仍然有點不清楚,但現在我明白了。 – itsmequinn 2012-02-05 01:09:22