2014-11-04 98 views
0

我对jQuery AutocompletejQuery的自动完成功能不能与多选选项显示

<script> 

    $(function() { 
    var availableTags = [ 
    {key: "1",value: "NAME 1"},{key: "2",value: "NAME 2"},{key: "3",value: "NAME 3"},{key: "4",value: "NAME 4"},{key: "5",value: "NAME 5"} 
    ]; 

    $("#project-name").autocomplete({ 
     minLength: 0, 
     source: availableTags, 
     focus: function(event, ui) { 
     $("#project-name").val(ui.item.value); 
     return false; 
     }, 
     select: function(event, ui) { 
     $("#project-name").val(ui.item.value); 
     $("#project-id").val(ui.item.key); 

     return false; 
     } 
     }); 

    }); 

    </script> 

<form action="search" method="post" > 
<input id="project-name" name="project2" id="searchbox"/> 
<input type="text" id="project-id" /> 
</form> 

输出上面的脚本的脚本

Correct Dispplay

效果很好,但如果我有添加选项multiselect: true,在配置上它不能很好地显示,多选也不能工作。

输出如果multiselect设置为true

Incorrect display

我怎么能允许多个选择与标签正确显示?

谢谢。

回答

2

您需要处理sourceselect回调中的多重选择。你的JavaScript更改为:

function split(val) { 
    return val.split(/,\s*/); 
} 

function extractLast(term) { 
    return split(term).pop(); 
} 

$("#project-name").autocomplete({ 
    minLength: 0, 
    source: function(request, response) { 
     // delegate back to autocomplete, but extract the last term 
     response($.ui.autocomplete.filter(
      availableTags, extractLast(request.term))); 
    }, 
    focus: function() { 
     // prevent value inserted on focus 
     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.value); 
     // add placeholder to get the comma-and-space at the end 
     terms.push(""); 
     this.value = terms.join(", "); 

     $("#project-id").val(ui.item.key); 

     return false; 
    } 
}); 

来源:https://jqueryui.com/resources/demos/autocomplete/multiple.html

Fiddle

+0

请问上面的脚本将数据转换为标签格式?另外我怎样才能像'ajax_call.php'而不是'availableTags'在'source'中调用动态URL? – Slimshadddyyy 2014-11-04 11:48:13

+0

@Slimshadddyyy不,但您可以使用如下插件:[https://github.com/aehlke/tag-it](https://github.com/aehlke/tag-it),它会将所选值转换为标签 – Victor 2014-11-04 11:58:40

+0

是的,您可以使用远程功能替换availableTags。示例:[http://jqueryui.com/autocomplete/#remote-jsonp](http://jqueryui.com/autocomplete/#remote-jsonp) – Victor 2014-11-04 12:00:57