我们如何使用Jquery tagit获取选定标签的ID?
-
11-12-2019 - |
题
我有一个输入标签字段,我想获取所选tages的ID
所以我试了一下 http://jsfiddle.net/u8zj5/19/ 但是我的问题我想获得id not标签
或值传递到 id="show"
但我失败了。
<input type="text" id="field1" name="field1" value=""/>
<span id="show">show ID here</span>
jQuery(document).ready(function(){
var availableTags = [{"id":"144","label":"Allicelabel","value":"Allice value"}];
jQuery("input#field1").each(function(){
var target = jQuery(this);
var currenttags = target.val();
target.hide()
.after("<ul class=\"tags\"><li>"+currenttags+"</li></ul>");
var instance = target.next();
instance.tagit({
tagSource:availableTags,
tagsChanged:function () {
var tags = instance.tagit('tags');
var tagString = [];
for (var i in tags){
tagString.push(tags[i].value);
}
$("#show").html(tagString.join(','));
},
sortable:true,
triggerKeys: ['enter', 'comma', 'tab']
});
});
});
这里有没有人用过 jQuery Tagit(演示页) 可以帮我解决这个问题
解决方案
我有同样的问题,我所做的是修改tag-it。js的。当您调用函数选择时,您需要发送 ID
通过功能 _addTag
self._addTag(ui.item.label, ui.item.value, ui.item.id);
然后你只需要获取id:
_addTag: function(label, value, id) {
...
this._addSelect(label, value, id);
...
}
在这里追加 ID
在隐藏的选择
_addSelect: function(label, value, id) {
var opt = $('<option>').attr({
'selected':'selected',
'value':id
}).text(label);
this.select.append(opt);
有了这个,你可以有一个标签的自动完成列表,一个值显示在标签,和 ID
在隐藏的选择。
其他提示
我有同样的问题,但不想改变插件的默认行为。所以,相反,我使用提供的钩子添加新的Behaivior。
var availableTags = [
{
label: "myTag",
value: "myTag",
id: 1
},
//etc...
];
var assignedTags = [];
$('#singleinputfield').tagit( {
tagSource: function (request, response) {
//setup the search to search the label
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(availableTags, function (value) {
return matcher.test(value.label);
}));
},
beforeTagAdded: function(event, ui){
//get id for that tag and signal if it was in the tagSource list
var id, result = false;
$.each(availableTags, function(){
if(ui.tagLabel === this.label){
result = true;
id=this.id;
return false;
}
});
if(result){
//put id in the list of ids we are using
assignedTags.push(id);
}
return result;
},
afterTagAdded: function(event, ui){
//replace the values in the single input field with the assigned ids
$('#singleinputfield').val(assignedTags.join(','));
},
afterTagRemoved: function(event, ui){
$('#singleinputfield').val(assignedTags.join(','));
},
beforeTagRemoved: function(event, ui){
var id;
//get the id for the removed tag and signal if it was in the tagSource list
$.each(availableTags, function(){
if(ui.tagLabel === this.label){
result = true;
id = this.id;
return false;
}
});
if(result){
//remove the unassigned tag's id from our list
assignedTags = $.grep(assignedTags, function(el){
return el != id;
});
}
}
});
. 使用类似选择2的其他插件。它实际上已经支持了这一点。
不隶属于 StackOverflow