I have a input control using as multiselection select2
<input class="form-control no-padding cTagID" tabindex="3" id="cTagID" name="cTagID" style="border:none;" />
I convert it to select2 and get data from ajax as below
$("#cTagID").select2({
placeholder: "Select a Tag",
allowClear: true,
width: '100%',
multiple: true,
maximumSelectionSize: 9,
escapeMarkup: function (text) { return text; },
minimumInputLength: 0,
ajax: {
url: '@Url.Action("myaction", "mycontroller")',
dataType: 'json',
quietMillis: 0,
cache: false,
type: "POST",
data: function (term, page) {
return {
q: term,
page: page,
listType: "mytype",
Searchterms: $("#iProjectId").val()
};
},
results: function (data, page) {
var more = (page * 30) < data.total_count; // whether or not there are more results available
return {
results: $.map(data.items, function (item) {
return {
text: item.text,
id: item.id
}
}),
more: more
}
},
cache: true
}
}).on("change", function () {
$(this).valid();
alert($("#cTagID").val()) // Problem is here ..Even if a selected item is removed by user it will still be available in val
});
Ajax call filter and pagination etc is working fine and I get data in below format
{
"total_count":6905,
"items":[
{
"id":"(DB-227)-Q14-SL03 ",
"text":"(DB-227)-Q14-SL03 ~ E_ELOOP "
},
{
"id":"(DB-227)-Q14-SL04 ",
"text":"(DB-227)-Q14-SL04 ~ E_ELOOP "
},
{
"id":"011100-727 ",
"text":"011100-727 ~ E_OTP "
},
]
}
The issue is if user select an item and then removes it it will remain as the val ("#cTagID").val() will return the removed item also