Select2标签按功能设置值 [英] Select2 tags set value by function
问题描述
我有一个select2,只有在获得许可的情况下,我才需要创建标签.我需要通过用户ID通过ajax来检查权限.
I've a select2 where i need to create tags only if I got permission. I need to check permission by ajax by user-id.
现在设置为 tags:true
,我可以始终创建新的标签.(好的)如果设置了 tags:false
,则无法创建新标签.(好)
Now setting is tags: true
and i can ALWAYS create new tags. (ok)
If a set tags: false
i can't create new tags. (ok)
我尝试使用标签: function(){return false;}
,但似乎仍可以创建标签.(不好)
I tried using tags: function() { return false; }
but seem tags can be created anyway. (bad)
我的目标是拥有这样的东西:
My goal is to have something like this:
tags: function() {
$.ajax({
type: "POST",
async: false,
dataType:"json",
url: "ajax/check_permissione.php",
data: { 'user-id': 1 },
success: function(data, status) {
if ( data.PermissionOK == 1 ) {
return true;
}
return false;
}
});
}
但是我现在不知道标签是否可以接受函数中的值?
But I don't know at this point if tags can accept value from a function?
我的脚本:
$("#test").select2({
tags: true, // <- if true create new tags, else only select available
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
$result.append(" <em>(new option)</em>");
}
return $result;
}
}).on('select2:select', function (e) {
//others operations
});
推荐答案
只需将 tags:true
更改为 tags:Permission
,其中 permission
包含指示用户标识是否具有权限的值.如果通过ajax检查权限,则可以将结果存储到变量中.这是插图.
Just change tags: true
into tags: permission
where permission
contains the value that indicates whether an user id has permission or not. If you check permission through ajax, you can store the result into the variable. Here is the illustration.
var permission = true;
$.ajax({
type: "POST",
async: false,
dataType:"json",
url: "ajax/check_permissione.php",
data: { 'user-id': 1 },
success: function(data, status) {
if ( data.PermissionOK == 1 ) {
permission = true;
} else {
permission = false;
}
}
});
如果您使用的是Ajax,请先执行此代码,然后再使用 select2
If you use ajax, execute this code first before using select2
这篇关于Select2标签按功能设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!