我有一个 jquery 自动完成字段,我想在同一个输入字段中添加多个值。在我在这里看到的示例中,http://jqueryui.com/demos/autocomplete/#multiple值和标签是相同的,因此在选择事件中的内容可以正常工作。但是,就我而言,当用户选择名称时,我希望输入框显示标签,但我想在提交表单时发布值。为了解决这个问题,我在表单中添加了一个隐藏字段,并有一个单独的数组来获取该值,但我的问题是当用户退格退出该值时。它仍然在我的阵列中。任何想法如何解决这个问题?或者也许是更好的解决方案?
var friend_data = [{"label":"JOhn Doe","value":"12345"},{"label":"Jane Doe","value":"123456"}];
$( "#friends" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
}).autocomplete({
minLength: 0,
//source: friend_data,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
friend_data, extractLast( request.term ) ) );
},
delay: 0,
autofocus: true,
focus: function(event, ui) {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.label );
friend_id_list.push( ui.item.value );
console.log(friend_id_list);
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
console.log(this.value);
return false;
}
})
.data( "autocomplete")._renderItem = function( ul, item ) {
var fb_pic_path = '<img src="http://graph.facebook.com/' + item.value + '/picture?type=square">' ;
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + fb_pic_path + item.label + "</a>" )
.appendTo( ul );
};