Select2 - disable the user input choice - javascript

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 !
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,
});

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;
}
});

Set tags to false. Example:
$('select').select2({
tags: false
});

Related

Use ajax to populate select2 only on open

I'm using the following code to fetch options from a database and populate a select2 on open. It works pretty well, but as soon as I start typing in the select2 search input box it also searches via the same ajax function. How can I just populate every time it opens, but then leave it there as long as it's opened?
Also since I'm using it to create tags I lost the ability to auto-select the new tag when I attached the ajax part, so instead of typing and pressing enter to add a tag, it's now stuck in search-land and I have to click on the newly created tag manually if I want it to be selected.
Any ideas?
function formatMenu (data) {
if (!data.id) { return data.text; }
var $data = $(
'<nobr>' + data.text + '</nobr>'
);
return $data;
};
$('select').select2({
templateSelection: formatMenu,
dropdownCssClass: 'select2-menu',
dropdownParent: $('#parent'),
placeholder: '-',
tags: true,
allowClear: true,
ajax: {
url: "?ajax=get_data,
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: false
},
sorter: function(data) {
return data.sort(function (a, b) {
a = a.text.toLowerCase();
b = b.text.toLowerCase();
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
return 0;
});
},
createTag: function (params) {
return {
id: params.term,
text: params.term
}
}
});

xeditable & select2 dropdown w/ajax source displaying empty after submitting

I've gotten xeditable and select2 to work with an api call as the source and everything works great EXCEPT the following.
After submitting the select2 dropdown, the value of the table is displayed as EMPTY and requires a page refresh in order to update to the correct value.
Does anyone know how to update the value to the selected select2 dropdown value?
my html:
<td class="eo_role"><a href="#" data-pk={{r.pk}} data-type="select2" data-url="/api/entry/{{r.pk}}/"
data-name="eo_role" data-title="Enter EO_role">{{r.eo_role}}</a></td>
here is my JS:
$('#example .eo_role a').editable( {
params: function(params) { //params already contain `name`, `value` and `pk`
var data = {};
data[params.name] = params.value;
return data;
},
source: 'http://localhost:8000/api/eo_role/select_two_data/',
tpl: '<select></select>',
ajaxOptions: {
type: 'put'
},
select2: {
cacheDatasource:true,
width: '150px',
id: function(pk) {
return pk.id;
},
ajax: {
url: 'http://localhost:8000/api/eo_role/select_two_data/',
dataType: "json",
type: 'GET',
processResults: function(item) {return item;}
}
},
formatSelection: function (item) {
return item.text;
},
formatResult: function (item) {
return item.text;
},
templateResult: function (item) {
return item.text;
},
templateSelection : function (item) {
return item.text;
},
});
Again - everything works (database updates, dropdownlist populates etc.) however the <td> gets updated with "EMPTY" after submitting the dropdown - requiring a page refresh to show the correct value.
I figured out a workaround. I'm SUPER PUMPED.
//outside of everything, EVERYTHING
//test object is a global holding object that is used to hold the selection dropdown lists
//in order to return the correct text.
var test = {};
$('#example .eo_role a').editable( {
params: function(params) { //params already contain `name`, `value` and `pk`
var data = {};
data[params.name] = params.value;
return data;
},
//MUST be there - it won't work otherwise.
tpl: '<select></select>',
ajaxOptions: {
type: 'put'
},
select2: {
width: '150px',
//tricking the code to think its in tags mode (it isn't)
tags:true,
//this is the actual function that triggers to send back the correct text.
formatSelection: function (item) {
//test is a global holding variable set during the ajax call of my results json.
//the item passed here is the ID of selected item. However you have to minus one due zero index array.
return test.results[parseInt(item)-1].text;
},
ajax: {
url: 'http://localhost:8000/api/eo_role/select_two_data/',
dataType: "json",
type: 'GET',
processResults: function(item) {
//Test is a global holding variable for reference later when formatting the selection.
//it gets modified everytime the dropdown is modified. aka super convenient.
test = item;
return item;}
}
},
});
I faced that same issue. I handle it that way:
In x-editable source code look for:
value2html: function(value, element) {
var text = '', data,
that = this;
if(this.options.select2.tags) { //in tags mode just assign value
data = value;
//data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc);
} else if(this.sourceData) {
data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc);
} else {
//can not get list of possible values
//(e.g. autotext for select2 with ajax source)
}
As you can see, there is else statment, without any code (only 2 comments) that is the situation, with which we have a problem. My solution is to add missing code:
(...) else {
//can not get list of possible values
//(e.g. autotext for select2 with ajax source)
data = value;
}
That's fix problem without tags mode enabled. I do not detect any unwanted behaviors so far.
Example code:
jQuery('[data-edit-client]').editable({
type: 'select2',
mode: 'inline',
showbuttons: false,
tpl: '<select></select>',
ajaxOptions: {
type: 'POST'
},
select2: {
width: 200,
multiple: false,
placeholder: 'Wybierz klienta',
allowClear: false,
formatSelection: function (item) {
//test is a global holding variable set during the ajax call of my results json.
//the item passed here is the ID of selected item. However you have to minus one due zero index array.
return window.cacheData[parseInt(item)].text;
},
ajax: {
url: system.url + 'ajax/getProjectInfo/',
dataType: 'json',
delay: 250,
cache: false,
type: 'POST',
data: {
projectID: system.project_id,
action: 'getProjectClients',
customer: parseInt(jQuery("[data-edit-client]").attr("data-selected-company-id"))
},
processResults: function (response) {
window.cacheData = response.data.clients;
return {
results: response.data.clients
};
}
}
}
});

jquery Select2: How to add attributes to li element in DropDown

I use the select2 plugin from jquery and get my data over an ajax load. When I set the response I want to add attributes to the li-elements of my dropdown.
I already tried it with calling a function in "templateResult" but there I can only give back the vakue which is IN the <li></li> tags
My javascript:
var autocomplete = function () {
$("body").find("#myDropDown").select2({
language: "es",
ajax: {
url: searchDataUrl,
type: "POST",
// dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
return {
results: data.userData,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
newTag: true // add additional parameters
}
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 3,
templateResult: formatReponse, //With this it doesnt work
});
};
And the function from my templateResult Call:
//When I do this, I have a "<li>"-Tag within a "<li>"-Tag
var formatReponse = function (data) {
return '<li data-id="'+data.id+'" class="select2-results__option" role="treeitem">'+data.text+'</li>';
};
Can anybody help me with this? THANKS!
use the .attr(att,val) function like this:
Give your <li> an id name like liID in <li id='liID'> the following example
then give the name of the attribute you want to change in the example given as attributeToChange then give the value you want to set in the atribute in the example: valueToSet. good luck
$('#liID').attr('attributeToChange', 'valueToSet');

Select2 - infinite scroll not loading next page with remote data

I am using Select2 4.0.1, I have used ajax to populate the result based on users input, but whenever I search for anything select2 lists first page result, but consecutive pages were not loading, also request is made for 2nd page on scroll. seems to be I am missing something.
$multiselect = $(element).select2({
closeOnSelect: false,
multiple: true,
placeholder: 'Assign a new tag',
tags: true,
tokenSeparators: [","],
ajax: {
url: '/search_url',
dataType: 'json',
type: 'GET',
delay: 250,
data: function(params) {
return {
search: params.term,
page: params.page
};
},
processResults: function(data, params) {
var more, new_data;
params.page = params.page || 1;
more = {
more: (params.page * 20) < data.total_count
};
new_data = [];
data.items.forEach(function(i, item) {
new_data.push({
id: i.name,
text: i.name
});
});
return {
pagination: more,
results: new_data
};
},
cache: true
}
})
Any help is much appreciated.Thnx:)
This is the code I got working last week. I am using a different transport on my end, but that shouldn't make a difference. I was having the same issue as you regarding the lack of paging working while scrolling. My issue ended up being that I didn't have the proper {'pagination':{'more':true}} format in my processResults function. The only thing I can see that may work for you is to "fix" the page count in the data function vs. the processResults function.
When you scroll to the bottom of your list, do you see the "Loading more results..." label? Have you attempted to hard code the more value to true while debugging?
this.$(".select2").select2({
'ajax': {
'transport': function (params, success, failure) {
var page = (params.data && params.data.page) || 1;
app.do('entity:list:search',{'types':['locations'],'branch':branch,'limit':100,'page':page,'term':params.data.term})
.done(function(locations) {
success({'results':locations,'more':(locations.length>=100)});
});
}
, 'delay': 250
, 'data':function (params) {
var query = {
'term': params.term
, 'page': params.page || 1
};
return query;
}
, 'processResults': function (data) {
return {
'results': data.results
, 'pagination': {
'more': data.more
}
};
}
}
, 'templateResult': that.formatResult
, 'templateSelection': that.formatSelection
, 'escapeMarkup': function(m) { return m; }
});

two ajax request url (success/fail)

Good day,
I was in some disarray . I have a ajax request from select2. Also I have two urls. How should I event organized If / else success/failure statements, if suddenly one will not work , then send an inquiry to another link?
I'm trying again and again and alwas there is error somewhere((
$(".js-data-example-ajax").select2({
language: "ru",
placeholder: "Serach.........",
disabled: false,
selected: true,
ajax: {
url: "url_1",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term + "%", // search term
};
},
processResults: function (data) {
if (data.features.length > 0) {
var resultArray = [];
$.each(data.features, function (index, value) {
value.attributes.id = value.attributes.OBJECT_ID;
resultArray.push(value.attributes);
});
return {
results: resultArray
};
} else {
return []
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 5,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
It should be quite simple because you only have to call the first url and, on error, call the second.
$.ajax(function(data){
url: "url_1",
...,
success(function(data){
//do stuff on success
}),
error(function(e){
$.ajax(function(data{
//call the second url
})
})
})

Categories