我正在使用jquery autocomplete。
我正在尝试关注代码
HTML
<textarea class="search-element"></textarea>
脚本
var data = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C++",
"Clojure",
"COBOL",
"ColdFusion"
];
$(function () {
var $this;
var singleSelectOptions = {
source: function (request, response) {
response($.map(data, function (item) {
return {
label: item,
}
}));
},
select: function (event, ui) {
$($this).autocomplete("close");
$($this).val($($this).val() + '\n' + ui.label)
},
minLength: 0,
open: function () {
$("ul.ui-menu").width($(this).innerWidth());
}
}
$(document).find('textarea[class*="search-element"]').live('keydown', function () {
$($this).autocomplete(singleSelectOptions);
}).live('focus', function () {
$this = $(this);
var text = $this.val();
if (text == '') {
$($this).autocomplete(singleSelectOptions);
$($this).autocomplete("search");
}
});
})
通过使用此代码,我一次只能选择一个选项 但我需要使用复选框
选择多个选项现在我的结果显示如下
但是我想要结果如下,当我们复选框时,自动完成不应该关闭,选择的选项应该用逗号分隔填写相关的textarea,当我们取消选中复选框时,那个选项应该从textarea中删除。我可以更新textarea的文本。
答案 0 :(得分:1)
我尝试过以下代码,我的目标是通过此实现的。
<强> HTML 强>
<textarea class="multiselect-element"></textarea>
<强>脚本强>
var data = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C++",
"Clojure",
"COBOL",
"ColdFusion"
];
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
function bindAutoComplete(ele, options) {
var text = ele.val();
text = text == null || text == undefined ? "" : text;
$(ele).autocomplete(options).data("autocomplete")._renderItem = function (ul, item) {
var checked = (text.indexOf(item.label + ', ') > -1 ? 'checked' : '');
return $("<li></li>")
.data("item.autocomplete", item)
.append('<a href="javascript:;"><input type="checkbox"' + checked + '/>' + item.label + '</a>')
.appendTo(ul);
};
}
$(function () {
var $this;
var multiSelectOptions = {
minLength: 0,
source: function (request, response) {
response($.map(data, function (item) {
return {
label: item
}
}));
},
focus: function () {
// prevent value inserted on focus
//$($this).autocomplete("search");
return false;
},
select: function (event, ui) {
var text = $this.val();
text = text == null || text == undefined ? "" : text;
var checked = (text.indexOf(ui.item.value + ', ') > -1 ? 'checked' : '');
if (checked == 'checked') {
this.value = this.value.replace(ui.item.value + ', ', '')
}
else {
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;
},
open: function () {
$("ul.ui-menu").width($(this).innerWidth());
}
}
$(document).find('textarea[class*="multiselect-element"]').live('keydown', function () {
bindAutoComplete($this, multiSelectOptions);
}).live('focus', function () {
$this = $(this);
var text = $this.val();
bindAutoComplete($this, multiSelectOptions);
$($this).autocomplete("search");
})
})
答案 1 :(得分:0)