Jquery UI自动完成MultiSelect无法正常工作

时间:2016-04-06 13:13:35

标签: jquery asp.net asp.net-mvc

我想出了我经常搜索的问题,并尝试了解决我的问题的所有方法但没有回应。我想在文本框中使用自动完成选择多个值,但我添加第一项自动完成不会在第一个值添加后加载值,如图所示。我的代码如下

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

function AutoCompleteMrnPatient() {
    $('#patientmrntxts').autocomplete({
        source: function (request, reponse) {
            $.ajax({
                url: "/DoctorAssessment/GetmrnNumber",
                type: "GET",
                dataType: "json",
                data: { term: request.term },
                success: function (data) {
                    reponse($.map(data, function (item) {
                       return { label: item.label, value: item.value };
                    }));
                }
            });
        },
        focus: function () {
            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(", ");
            return false;
        }
    });
}

enter image description here

1 个答案:

答案 0 :(得分:0)

我有机会看一下这个。我做了以下假设和观察:

  • 您只需要唯一的值,没有重复项 - 所以我只保留新值(如果它们是唯一的)
  • 您的值不包含逗号 - 这会使拆分功能复杂化
  • 您可能需要跟踪这些值并对其执行某些操作。因此,我将它们推入一个名为“holder”的数组中 - 请注意,如果从列表中删除选择,我不会删除值 - 您可以使用我提供的函数(查找和删除它们的方法等)来执行此操作。 )
  • 您必须确定是否要显示商品的价值或标签。
  • 我没有对您的标签/值对进行适当的测试,因此我创建了一个。我假设你的ajax工作 - 所以我评论说我的测试并使用了我创建的对象列表的来源。
  • 您的source错误地将“回复”拼写为“响应”,但我没有解决这个问题。
  • AutoCompleteMrnPatient基本上与文档就绪处理程序相同。

代码:(包括设置,对象列表上的实用程序的一些函数,然后是您需要的代码。)

// just for a testable solution (source)
var availableTags = [
  "AppleScript",
  "AppleScript",
  "Apple-Script",
  "Apple Script",
  "AppleScript",
  "Asp",
  "BASIC",
  "C",
  "C++",
  "Clojure",
  "COBOL",
  "ColdFusion",
  "Erlang",
  "Fortran",
  "Groovy",
  "Haskell",
  "Java",
  "JavaScript",
  "Lisp",
  "Perl",
  "PHP",
  "Python",
  "Ruby",
  "Scala",
  "Scheme"
];
// create a new array of label/value to match the question
// http://stackoverflow.com/questions/36452275/jquery-ui-autocomplete-multiselect-not-working
var newarr = [];
for (var a = 0; a < availableTags.length; a++) {
  newarr.push({
    label: availableTags[a],
    value: availableTags[a] + "v" + a
  });
}

功能部分:

// some namespaced functions to use
var myApp = myApp || {};
myApp.arrayObj = {
  indexOf: function(myArray, searchTerm, property) {
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) return i;
    }
    return -1;
  },
  indexAllOf: function(myArray, searchTerm, property) {
    var ai = [];
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) ai.push(i);
    }
    return ai;
  },
  lookup: function(myArray, searchTerm, property, firstOnly) {
    var found = [];
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) {
        found.push(myArray[i]);
        if (firstOnly) break; //if only the first 
      }
    }
    return found;
  },
  lookupAll: function(myArray, searchTerm, property) {
    return this.lookup(myArray, searchTerm, property, false);
  },
  remove: function(myArray, searchTerm, property, firstOnly) {
    for (var i = myArray.length - 1; i >= 0; i--) {
      if (myArray[i][property] === searchTerm) {
        myArray.splice(i, 1);
        if (firstOnly) break; //if only the first term has to be removed
      }
    }
  }
};
myApp.func = {
  split: function(val) {
    return val.split(/,\s*/);
  },
  extractLast: function(term) {
    return this.split(term).pop();
  }
};

// test a lookup
//var ai = myApp.arrayObj.lookupAll(newarr, "AppleScript", "label");
//console.dir(ai);

// test an index of an item
//var myi = myApp.arrayObj.indexOf(newarr, "AppleScript", "label");
//console.log(myi);

// test remove of item match (all of them)
// var removeFirstOnly = false;
//myApp.arrayObj.remove(newarr, "AppleScript", "label", removeFirstOnly);
//console.dir(newarr);


// put the result objects in this array
var holder = [];

function AutoCompleteMrnPatient() {
  $('#patientmrntxts').autocomplete({
    source: function(request, response) {
      // delegate back to autocomplete, but extract the last term
      response($.ui.autocomplete.filter(
        newarr, myApp.func.extractLast(request.term)));
    },
    /* commented out and use the source above
    source: function(request, reponse) {
       $.ajax({
         url: "/DoctorAssessment/GetmrnNumber",
         type: "GET",
         dataType: "json",
         data: {
           term: request.term
         },
         success: function(data) {
           reponse($.map(data, function(item) {
             return {
               label: item.label,
               value: item.value
             };
           }));
         }
       });
     },
     */
    focus: function() {
      return false;
    },
    select: function(event, ui) {
      // put this in a "holder" array if not in there already
      var exists = myApp.arrayObj.indexOf(holder, ui.item.value, "key");
      if (exists === -1) {
        var entry = {
          key: ui.item.value,
          term: myApp.func.extractLast(this.value),
          item: ui.item
        };
        holder.push(entry);
      }
      console.dir(holder);
      var terms = myApp.func.split(this.value); // contains entry ex:"Asp, b"
      // remove the current input
      terms.pop();
      // check if duplicate and if not push it in
      if (exists === -1) {
        //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(", ");
      return false;
    }
  }).data("uiAutocomplete")._renderItem = function(ul, item) {
    return $("<li></li>")
      .data("item.autocomplete", item.label)
      .attr("data-value", item.value)
      .append("<a>" + item.label + "</a>")
      .appendTo(ul);
  };
}
AutoCompleteMrnPatient();

以上是上述工作的示例:https://jsfiddle.net/xvu9syuf/1/