I'm not sure if i'm going about this the correct way, but if you have any constructive comment that can help lead me in the right direction please share. I've been stuck on this for quite some time.
I have the following select2 control that is loading the entire table for a field of that table. There is a function with select2 called minimumInputLength, which still seems to load the table in it's entirety instead of querying on the first three characters. The pagination works correctly as shown in this fiddle.js: http://jsfiddle.net/jgf5fkfL/66/
$.fn.select2.amd.require(
['select2/data/array', 'select2/utils'],
function (ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
function contains(str1, str2) {
return new RegExp(str2, "i").test(str1);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
if (!("page" in params)) {
params.page = 1;
}
var pageSize = 50;
var results = this.$element.children().map(function (i, elem) {
if (contains(elem.innerText, params.term)) {
return {
id: [elem.innerText, i].join(""),
text: elem.innerText
};
}
});
callback({
results: results.slice((params.page - 1) * pageSize, params.page * pageSize),
pagination: {
more: results.length >= params.page * pageSize
}
});
};
$(".js-example-basic-multiple").select2({
ajax: {},
minimumInputLength: 3,
allowClear: true,
width: "element",
dataAdapter: CustomData
});
});
The problem is my view is loading the entire table for active students on the rendering of the html.
def multisearch(request):
userid = ADMirror.objects.filter(student_status_id = 1).values('studentntname').values_list('studentntname', flat=True)
args = {'userid':userid}
return render(request, 'multisearch.html',args)
I render the html and select2 control with:
{% block extra_js %}
{{ block.super }}
{{ form.media }}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src= "{% static '/search/user_select2.js' %}" type="text/javascript"></script>
<div class="col"><h4 style="margin-top: 0"><strong>Student ID Search</strong></h4><select class="js-example-basic-multiple" value = "{{ userid }}" style="width: 1110px" required>
{% for user in userid %}
<option value="{{ user }}"> {{ user }}</option>
{% endfor %}
</select>
Now I know how to prevent the loading of the data in my filter, which I do with the following, but how can I get this to work with my view and select2's minimum input length:
# doesn't load data on the initial load of the search.html page
def __init__(self, *args, **kwargs):
super(StudentFilter, self).__init__(*args, **kwargs)
# at startup user doen't push Submit button, and QueryDict (in data) is empty
if self.data == {}:
self.queryset = self.queryset.none()
I've also tried the following options with select2 and javascript unsuccessfully, because the data doesn't seem searchable :
$(document).ready(function () {
$('.js-example-basic-multiple').select2({
minimumInputLength: 3,
allowClear: true,
placeholder: {
id: -1,
text: 'Enter the Student id.',
},
ajax: {
type: 'POST',
url: '',
contentType: 'application/json; charset=utf-8',
async: false,
dataType: 'json',
data: function (params) {
return "{'searchFilter':'" + (params.term || '') + "','searchPage':'" + (params.page || 1) + "'}";
},
processResults: function (res, params) {
var jsonData = JSON.parse(res.d);
params.page = params.page || 1;
var data = { more: (jsonData[0] != undefined ? jsonData[0].MoreStatus : false), results: [] }, i;
for (i = 0; i < jsonData.length; i++) {
data.results.push({ id: jsonData[i].ID, text: jsonData[i].Value });
}
return {
results: data.results,
pagination: { more: data.more,
},
};
},
},
});
});
How can I get my data to not load until the minimum inputlength of select2 is met and still be searchable? I'm having to wait for the entire table to load before I can search and return results.
Certainly too late for a response. but in case it helps someone else. I got mine to work this way:
$("#select-company").select2({
ajax: {
url: "/en/entreprises.json", //URL for searching companies
dataType: "json",
delay: 200,
data: function (params) {
return {
search: params.term, //params send to companies controller
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
placeholder: "Start typing",
minimumInputLength: 3,
});
$("#selctor").select2({
placeholder: ".................. choos ....................",
//dropdownCssClass: 'smalldrop',
width: '100%',
ajax: {
url: "/search RUL",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params,
// page: params.page
};
},
results: function (data, search) {
return {
results: data.items
};
},
cache: true
},
templateResult: function (item) {
if (item.loading) return item.text;
return item.text;
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 3,
});
I think that the minimumInputLength it only works if you haven't loaded your options (ajax load). In your code the select has the options loaded at the beginning so minimumInputLength will not work.
So if you populate all the options at the page load the minimumInputLength will no affect.
Hope the solution goes this way.
Related
I have a select2 list which having huge data. So, basically on scrolling we're populating data through pagination( adding 10 records on each scroll). In Select2, version 3.4.8, its working fine and able to load data through asp.net web method. Below is the code
$("#ddlEntity").select2({
width: 200,
dropdownAutoWidth: true,
loadMorePadding: 200
initSelection: function (element, callback) {
var data = { id: ID, text: Value };
callback(data);
},
query: timedelayfunction(function (query) {
var res = AjaxRequest( URL , 'GetOnDemandWebMethod', { searchFilter : query.term, pageCounter: query.page, uid:$('#uid').val() });
var data = { more: (res.d[0] != undefined ? res.d[0].MoreStatus : false), results: [] }, i;
for (i = 0; i < res.d.length; i++) {
data.results.push({ id: res.d[i].ID, text: res.d[i].Value });
}
query.callback(data);
}, 200)
});
After moving Select2, version 4.0.3, same functionality is breaking. Can anyone help on this.
Thanks in Advance.
Finally, I've resolved it at my end and after tweaking web method response as JSON serialised array string and select2 v4 with data portion as json string worked for me.
for others it would be simple as like below code
$('#ddlEntity').select2({
width: 200,
allowClear: true,
placeholder: {
id: -1,
text: "Select any."
},
ajax: {
type:"POST",
url: '',
contentType: "application/json; charset=utf-8",
async: false,
dataType: 'json',
data: function (params) {
return "{'searchFilter':'" + (params.term || "") + "','searchPage':'" + (params.page || 1) + "'}";
},
processResults: function (res, params) {
var jsonData = JSON.parse(res.d);
params.page = params.page || 1;
var data = { more: (jsonData[0] != undefined ? jsonData[0].MoreStatus : false), results: [] }, i;
for (i = 0; i < jsonData.length; i++) {
data.results.push({ id: jsonData[i].ID, text: jsonData[i].Value });
}
return {
results: data.results,
pagination: {
more: data.more
}
};
}
}
});
Below is my code copied from https://select2.github.io/examples.html to load remote data via Select2 in my Asp.net MVC 4 project, which displayed in a Bootstap Modal dialog, however, it always shows "params.page" is undefined, it do worked if I put a "page:1" there. What's the problem?
$("#ReportToEmployeeName").select2({
placeholder: "Select Report To",
ajax: {
url: 'myurl ',
dataType: 'json',
delay: 250,
data: function (params) {
console.log(params);
return {
term: params.term, // search term
page: params.page //Undefined error here
//page: 1 // do worked, but then pagination will not work
};
},
processResults: function(data, params) {
params.page = params.page || 1;
return {
results: data.Results,
pagination: {
more: (params.page * pageSize) < data.Total
}
};
},
cache: true
},
//escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
allowClear: true,
//templateResult: formatRepo, // omitted for brevity, see the source of this page
//templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
I have the following select2 ajax call. How do I use the jquery $.map() to parse the returned json results. From the users array i need to get the Text and Value results. From the pager array I need to get the TotalItemCount. What I have below doesnt seem to work i.e the search results don't seem to display in the select list. No console errors are shown either so I'm not sure what Im doing wrong.
var url = '#Url.Action("GetEmployees", "Employees")';
var pageSize = 20;
$(".js-data-example-ajax").select2({
ajax: {
url: url,
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: $.map(data, function (users) {
return {
text: users.Text,
id: users.Value
}
}),
pagination: {
more: (params.page * pageSize) < data.pager.TotalItemCount
}
};
},
cache: true
},
minimumInputLength: 2,
placeholder: "-- Select --",
allowClear: true
});
The json returned is as follows:
{
"pager":{
"PageCount":1,
"TotalItemCount":1,
"PageNumber":1,
"PageSize":20,
"HasPreviousPage":false,
"HasNextPage":false,
"IsFirstPage":true,
"IsLastPage":true,
"FirstItemOnPage":1,
"LastItemOnPage":1
},
"users":[
{
"Disabled":false,
"Group":null,
"Selected":false,
"Text":"Joe Blogs",
"Value":"97306aa4-d423-4770-9b45-87a701146b10"
}
]
}
I was correct. I wasn't using the jQuery.map() correctly. It should be as follows:
results: $.map(data.users, function (users) {
return {
text: users.Text,
id: users.Value
}
}),
I'm developing a form with select2JS.
In my first step I use a simple Select2
$(this).select2();
But I want to change it for an Ajax version.
$(this).select2({
multiple:multival,
ajax:
{
url: '/api/v2/vocabulary/'+vocabulary+'/words/list',
headers: {'X-AUTHORIZATION-TOKEN': token},
dataType: 'json',
type: "POST",
quietMillis: 100,
data: function (params) { // Lors d'une recherche
return {
pattern: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.words,
pagination: {
more: (params.page * 15) < data.total
}
};
},
initSelection : function (element, callback) {
var data = [];
$(element.val()).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
cache: true
},
escapeMarkup: function (markup) {return markup; }, // let our custom formatter work
minimumInputLength: 0,
templateResult: function formatRepo (repo)
{
return repo.name;
},
templateSelection: function formatRepoSelection (repo)
{
return repo.name;
}
});
In the first version, my Ajax return the name of the Option ( When I send the form). In the Ajax version, the script create a new Option inside the select ( But not visible ) and when I send the form its an Id who is sent. Because in the Value of the new Option, its the Id and not the name.
I use Select2 4.0.1 and I find in the 3162' Line :
if (data.id) {
option.value = data.id;
}
I tried to change data.id by data.name, but it was not effective.
Do you have an idea?
I have this select2 code in my html (mvc with razor) page:
$('#QuickSearchState').select2({
minimumInputLength: 3,
width: 'resolve',
ajax: {
url: '#Url.Action("QuickSearchState", "DataCenter")',
contentType: 'application/json',
dataType: 'json',
type: 'POST',
traditional: true,
quietMillis: 400,
data: function(term, page) {
var data = {
term: term
};
return data;
},
results: function(data, page) {
return { results: data };
}
},
initSelection: function(element, callback) {
var data = { id: element.val(), text: element.val() };
callback(data);
},
formatResult: function(format) {
return format.label;
},
formatSelection: function(format) {
//this is a knockout view model
vmNewAddress.IdState(format.id);
vmNewAddress.StateName(format.stateName);
return format.label;
},
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) { return m; }
});
But i have another select in my code that can set a state in this select, but i dont know how to set this value to that select.
In my html i have this:
<select class="width-xl" data-bind="options: vm.GivenLocationsForConnection, optionsText: 'DisplayFormat', value: SelectedLocation"></select> -> first select that can fill the second state search select with a state
#Html.Hidden("query", null, new { #id = "QuickSearchState", #class = "width-xl", placeholder = "Ej. Montevideo" }) -> second select, this is a search for states and selects a single state
I am not sure if this is what you want but if you only want to select a value in the select you can just do below
$("#QuickSearchState").select2("val", "<YOUR VALUE>");