2012-02-04 84 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