Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 - disable the user input choice

I'm trying to set datas from ajax in a select2 select...

But the problem is that if I write something which isn't in my datas i can select this choice !

enter image description here

And this will take this value "I don't exist" ... The formatNoMatches() function seems not to be called ...

JS :

$(".select2-ajax").select2({
ajax: {
url: "ajax.call.php",
type:'POST',
dataType: 'json',
data: function (params) {
  return {
    nom: params.term, // search chars
    page: params.page,
  };
},
processResults: function (data, page) {
console.log(data.data);
if(typeof(data.data)=='undefined' || !data.data || data.data.length <= 0)
  var res = [];
else
{
  var res = [];
  for (var i = data.data.length - 1; i >= 0; i--) 
  {
    res.push({"text":data.data[i]["nom"]+' '+data.data[i]["prenom"],"id":data.data[i]["id_salarie"]});
  };
}
return { results: res};
},
cache: true
 },
formatNoMatches: function( term ) {
return "<li class='select2-no-results'>' "+term+" ': Aucun  résultat</li>";
},

allowClear: true,
language: 'fr',
multiple: false,

I tried the two following after seeing THIS question : ( but still don't work )

selectOnBlur:false,
createSearchChoice: false,



escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
});
like image 317
Seba99 Avatar asked Jul 16 '26 07:07

Seba99


1 Answers

This should only happen if you are returning an option from your server that matches the text the user entered or you are using the tags option.

Since you don't appear to be using tags, and your code doesn't include it, you can ensure this is not the issue by overriding createTag (previously createSearchChoice to always return null.

$('select').select2({
  createTag: function () {
    // Disable tagging
    return null;
  }
});
like image 166
Kevin Brown-Silva Avatar answered Jul 18 '26 21:07

Kevin Brown-Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!