I asked a question earlier today (jquery select2: error in getting data from php-mysql). However, I am trying to fix it and doing that now I am getting bit strange issue. I am n
Tags need an id and a text. The issue you're facing is that your text doesn't match the id.
So, even if you write the same text, Select2 thinks the new text is a new option because the id don't match.
To solve your issue, you need to set the id with the same value as the text. Change the foreach of your fetch.php
to the following:
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
Update:
You also need to update the variable lastResults
to avoid the duplication of tags with the same text. When you bind select2, you need to change the results
property of ajax
to this (based on this answer:
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function(term) {
return {q: term};
},
results: function(data) {
lastResults = data.results;
return {results: data};
},
},
Note the lastResults = data.results;
. Without this, the lastResults
variable is always empty and, when the createSearchChoice
function is executed, it will always return a new tag.