有谁知道我们如何在select2中设置标签的最大长度。 下面是我的代码,在这段代码中我可以创建长标签(15-20)。我想将它限制为10个字符。
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
我不是在寻找minimumInputLength或maximumSelectionSize。
答案 0 :(得分:1)
听起来您正在寻找maximumInputLength
选项。这将限制自定义标签和搜索时允许的长度。
答案 1 :(得分:0)
https://jsfiddle.net/Physcocybernatics/jvpsqy4o/3/
<select id="tags" multiple="multiple">
<option selected="selected">Kerry</option>
<option selected="selected">Cork</option>
</select>
$("#tags").select2({
tags: true,
tokenSeparators: [',', ' '], //allow tags when space or , is pressed
createTag: function (params) {
// don't allow tags which are less than 3 charackter
if (params.term.length < 11) {
// Return null to disable tag creation
return null;
}
return {
id: params.term,
text: params.term
}
}
});
params.term.length 是我获取标签长度的方法
返回null 禁用标签创建