what i’m trying to achieve is that, to add new tags and get them selected and posted “as selection” to server upon clicking submit button in the form.
here the Jquery:
$("#SelectedRoots").select2({
tokenSeparators: [','],
multiple: true,
placeholder: 'Select an option',
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
newTag: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newTag) {
$result.append(" <em><strong> (New) </strong></em>");
}
return $result;
},
tags: true
}).on("select2:select", function (e) {
if (e.params.data.tag == false) {
return;
}
var select2element = $(this);
if (e.params.data.newTag === true) {
$.ajax({
url: "/Roots/newRoot",
data: { "rooting": e.params.data.text },
dataType: "json",
type: "POST",
success: function (res) {
data = {
"id": res.rootID,
"text": res.rooting,
}
var selection = select2element.val();
var index = selection.indexOf(res.rooting);
console.log("selection =", selection);
console.log("index =", index);
if (index !== -1) {
selection[index] = res.rootID.toString();
}
$('option#' + res.rooting, select2element).attr('id', res.rootID);
select2element.trigger("change");
console.log("selection after=", selection);
console.log("index after =", index);
},
});
}
});
what happens is that only last option is added.
console log shows the following :
selection = (3) ["2212", "2214", "new tag"]
1:5075 index = 2
1:5084 selection after= (3) ["2212", "2214", "2216"]
1:5085 index after = 2
1:5074 selection = (4) ["2212", "2214", "new tag", "new new tag"]
1:5075 index = 3
1:5084 selection after= (4) ["2212", "2214", "new tag", "2217"]
1:5085 index after = 3
as you see, the last one has id, however previous new added tag lost the id.
i believe there should be some iteration of new added tags, but do not know to to do it. Please help.