jQuery自动完成功能不会显示多选选项

时间:2014-11-04 11:14:33

标签: jquery jquery-ui-autocomplete

我的jQuery Autocomplete

脚本
<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设置为真,则输出

Incorrect display

如何通过正确显示标签来允许多项选择?

感谢。

1 个答案:

答案 0 :(得分: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