Jquery tagit을 사용하여 선택한 태그의 ID를 어떻게 얻을 수 있나요?
-
11-12-2019 - |
문제
입력 태그 필드가 있고 선택한 테지의 ID를 얻고 싶습니다. http://jsfiddle.net/u8zj5/19/ 하지만 내 문제는 신분증이나 값을 전달하지 않기를 원합니다. 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;
});
}
}
});
. Select2와 같은 다른 플러그인을 사용하십시오.실제로이 기능을 지원했습니다.
제휴하지 않습니다 StackOverflow