在rails 4.0中,我使用的是select2()插件。在此字段中,我只需要输入唯一标记,但现在它正在接受重复的条目。如何避免重复输入?请帮我解决这个问题。
在观看中,
<script type="text/javascript">
$('#DIV_USERNAME').select2({
placeholder: "Search for a names",
multiple: true,
ajax: {
url: "autocomplete/names",
dataType: 'json',
data: function (term) {
return { q: term };
},
results: function (data) {
return {results: data};
}
},
createSearchChoice: function (term) {
return { id: term, text: term };
}
});
</script>
答案 0 :(得分:0)
检查以下选择事件,并在 createSearchChoice
中设置 isNew 属性让我知道它是否解决了您的问题
$('#some_id').select2({
tags: true,
tokenSeparators: [","],
createSearchChoice: function (term, data) {
if (term.trim().length > 0) {
if ($(data).filter(function () {
return this.text.toLowerCase().localeCompare(term.toLowerCase()) === 0;
}).length === 0) {
return {
id: term,
text: term,
isNew: true // this is necessary to check if the item is newly added or not
};
}
}
},
multiple: true,
minimumInputLength: 1,
allowClear: true,
data: [
{id: 1, text: 'some text'},
{id: 2, text: 'some other text'},
{id: 3, text: 'some more text'}
],
}).on("select2-selecting", function (e) {
var tagId = '';
if (e.choice.isNew) {
self.AddTagToDatabase(e.choice.text);
} else {
var isValidTag = true;
$(config.element[0] + ' ul li').find('div').each(function (index, item) {
if ($(item).html().toLowerCase().trim() == e.choice.text.toLowerCase().trim()) {
isValidTag = false;
e.choice.text = '';
return;
}
});
}
})