如果一个输入框可以接受多个输入项,比如选择你喜欢的语言,以逗号隔开,这是也可以使用AutoComplete为每个输入项提供输入提示。不过此时除了设置数据源外,还需要添加一些事件处理。
1
2
3
4
5
6
7
8
9
10
11 $(function () {
12 var availableTags = [
13 "ActionScript",
14 "AppleScript",
15 "Asp",
16 "BASIC",
17 "C",
18 "C++",
19 "Clojure",
20 "COBOL",
21 "ColdFusion",
22 "Erlang",
23 "Fortran",
24 "Groovy",
25 "Haskell",
26 "Java",
27 "JavaScript",
28 "Lisp",
29 "Perl",
30 "PHP",
31 "Python",
32 "Ruby",
33 "Scala",
34 "Scheme"
35 ];
36 function split(val) {
37 return val.split(/,\s*/);
38 }
39 function extractLast(term) {
40 return split(term).pop();
41 }
42
43 $("#tags")
44 // don't navigate away from the field on tab
45 //when selecting an item
46 .bind("keydown", function (event) {
47 if (event.keyCode === $.ui.keyCode.TAB &&
48 $(this).data("ui-autocomplete").menu.active) {
49 event.preventDefault();
50 }
51 })
52 .autocomplete({
53 minLength: 0,
54 source: function (request, response) {
55 // delegate back to autocomplete,
56 // but extract the last term
57 response($.ui.autocomplete.filter(
58 availableTags, extractLast(request.term)));
59 },
60 focus: function () {
61 // prevent value inserted on focus
62 return false;
63 },
64 select: function (event, ui) {
65 var terms = split(this.value);
66 // remove the current input
67 terms.pop();
68 // add the selected item
69 terms.push(ui.item.value);
70 // add placeholder to get the
71 //comma-and-space at the end
72 terms.push("");
73 this.value = terms.join(", ");
74 return false;
75 }
76 });
77 });
78
79
80
81
82
83
84
85
86