I have been using Select2 version 3 for my dropdowns for a while. However, I am trying to upgrade to the latest v4 release and am struggling to understand their documentation. Would someone be able to point me in the right direction in converting the below v3.5 code to v4 so that I can understand how to convert the rest of my code?
$("##hp.ID").select2(
{
dropdownAutoWidth: true,
minimumInputLength: 0,
allowClear: getBool("#hp.bAllowClear"),
width: "#hp.Width",
formatResult: formatResults,
formatSelection: formatSelection,
matcher: SetMatcher,
sortResults: SortSelect2,
initSelection: function (element, callback)
{
var id = "#Model"
if ((id != "") && (id != "0") && (id != undefined))
{
$.ajax("#Url.Action("GetVendorsInit", "DropDownManagerAjax")",
{
data: JSON.stringify({ VendorID: id }),
dataType: "json"
}).done(function (data)
{
callback({ id: data.id, text: data.text });
});
}
},
ajax: {
url: "#Url.Action("GetVendors", "DropDownManagerAjax")",
dataType: 'json',
quietMillis: 250,
data: function (term, page)
{
return {
q: term,
iDisplayStart: (page - 1) * 100,
iDisplayLength: 100,
sEcho: 0,
iSortCol_0: 0,
sSortDir_0: 'asc',
};
},
results: function (data, page)
{
var more = (page * 30) <= data.total;
return { results: data.data, more: more };
},
cache: true
},
dropdownCssClass: "autoWidth",
escapeMarkup: function (m) { return m; },
placeholder: 'Select Vendor...'
});
Related
I am using select2 dropdown. It's working fine for smaller number of items.
But when the list is huge (more than 40000 items) it really slows down. It's slowest in IE.
Otherwise simple Dropdownlist works very fast, till 1000 records. Are there any workarounds for this situation?
///////////////**** Jquery Code *******///////////////
var CompanypageSize = 10;
function initCompanies() {
var defaultTxtOnInit = 'a';
$("#DefaultCompanyId").select2({
allowClear: true,
ajax: {
url: "/SignUpTemplate/GetCompanies",
dataType: 'json',
delay: 250,
global: false,
data: function (params) {
params.page = params.page || 1;
return {
keyword: params.term ? params.term : defaultTxtOnInit,
pageSize: CompanypageSize,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.result,
pagination: {
more: (params.page * CompanypageSize) < data.Counts
}
};
},
cache: true
},
placeholder: {
id: '0', // the value of the option
text: '--Select Company--'
},
width: '100%',
//minimumInputLength: 3,
});
}
//////////******* Have to initialise in .ready *******///////////////
$(document).ready(function () {
initCompanies();
});
//////////******* C# code :: Controller is : SignUpTemplateController************/////
public JsonResult GetCompanies(string keyword, int? pageSize, int? page)
{
int totalCount = 0;
if (!string.IsNullOrWhiteSpace(keyword))
{
List<Companies> listCompanies = Companies.GetAll(this.CurrentTenant, (keyword ?? string.Empty).Trim(), false, 11, page.Value, pageSize.Value, ref totalCount, null, null, null, null, null).ToList();
var list = listCompanies.Select(x => new { text = x.CompanyName, id = x.CompanyId }).ToList();
return Json(new { result = list, Counts = totalCount }, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
I just upgraded my select2 to the latest version in the subject and noticed that more loading stopped working.
select.select2({
placeholder: select.data("placeholder"),
allowClear: true,
multiple: select.attr('multiple') ? true : false,
ajax: {
url: '/Common/GetEntityItems',
dataType: 'json',
delay: 250,
data: function(term, page) {
return {
searchTerm: term,
page: page
};
},
processResults: function (data) {
var more = true;
return { results: data.items, more: more };
},
error: function (e) {
alert('error!');
},
formatResult: function (item) {
return '<div>' + item.text + '</div>';
},
formatSelection: function (item) {
return item.text;
}
}
});
Despite the unconditional true to more variable, more thing doesn't work any more. Do you see anything I am missing?
Brad,
in case you still looking for answer (it took me a couple of hours btw), you need to change
return { results: data.items, more: more };
to
return { results: data.items, pagination: { more: more } };
/Fred
I am using jquery automcomplete with the Ajax call but what i want is if part is present in the json data fetched by the ajax on first call then i want to return that data as it is without giving the ajax call i have tried it as below
function SearchText() {
var cache = {};
$("#txtItem").autocomplete({
source: function (request, response) {
var term = request.term;
$.each(cache, function (index, value) {
$.each(value, function (index, value) {
if (value.indexOf(term) >= 0) {
response(cache[term]);
return;
}
});
});
cache = {};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{'item':'" + document.getElementById('txtItem').value + "'}",
dataType: "json",
success: function (data) {
cache[term] = data.d;
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
minLength: 3
});
}
but even if it finds the matching term in the array then also it generates the ajax call.
I m stuck here for 3 hrs now any help would be great. I have tried maxCacheLength but it is also not working.
Try this out, sometime ago i faced same problem and came up with this it might work for you
function SearchText() {
var cache = {};
var oldterm;
$("#txtItem").autocomplete({
source: function (request, response) {
if (request.term.indexOf(oldterm) >= 0) {
if (typeof (oldterm) != 'undefined') {
var data = jQuery.grep(cache[oldterm],
function (ele) {
return (ele.indexOf(request.term) >= 0);
});
response($.map(data, function (item) {
return { value: item }
}))
return;
}
} else {
cache = {};
$.ajax({
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{ 'item': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
oldterm = request.term;
cache[request.term] = data.d;
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (result) {
alert("Error");
}
});
}
},
minLength: 3,
select: function (event, ui) {
if (ui.item) {
formatAutoComplete(ui.item);
}
}
});
}
Here is a solution i found for you, It uses jQuery UI's autocomplete using cache and $.map function
function SearchText() {
var cache = {};
$("#textbox").autocomplete({
source: function(request, response) {
if (request.term in cache) {
response($.map(cache[request.term].d, function(item) {
return { value: item.value, id: item.id }
}))
return;
}
$.ajax({
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{ 'term': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json",
dataFilter: function(data) { return data; },
success: function(data) {
cache[request.term] = data;
response($.map(data.d, function(item) {
return {
value: item.value,
id: item.id
}
}))
},
error: HandleAjaxError
});
},
minLength: 3,
select: function(event, ui) {
if (ui.item) {
formatAutoComplete(ui.item);
}
}
});
}
Hope this helps.
I am using jqxgrid and I have below code snippet and i want to display load indicator on button click which calls the Ajax method and hide it on the success method or anyway other to display it as i need to show loading indicator from the time request made till i get the data
$("#btnSearch").bind('click', function () {
//show indicator here
LoadLookUpSearchGrid();
}
//Ajax call to fetch data
function LoadLookUpSearchGrid() {
var filterRows = getGridRows();
$.ajax({
type: 'POST',
dataType: 'json',
async: false,
cache: false,
url: 'AddEditView.aspx/LoadLookUpSearchGrid',
data: JSON.stringify({ FilterType: $('select#ddlFilterType').val() , Id: $("#txtId").val() , Name: $("#txtName").val(), SearchText: '', FilterRows: filterGridRows}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
var source = data.d;
SetSearchFields($('select#ddlFilterType option:selected').text(), source);
},
error: function (err) {
alert(err.text + " : " + err.status);
}
});
};
//source object to format data
function SetSearchFields(fieldName, source) {
var columns;
if (fieldName == "Operating Company") {
source =
{
datatype: "xml",
datafields: [
{ name: 'COMPANY', type: 'string' },
{ name: 'DESCR', type: 'string' }
],
async: false,
root: "Company",
localdata: source
};
columns = [
{ text: 'OPCO ID', dataField: 'COMPANY', width: '30%' },
{ text: 'Company Name', dataField: 'DESCR', width: '65%' }
];
}
lookupSearchResultGrid(source, columns,fieldName);
}
//adaptor to fill source and bind grid
function lookupSearchResultGrid(source, columns,fieldName) {
var searchViewGridDataAdapter = new $.jqx.dataAdapter(source);
$("#divLookupSearch").jqxGrid(
{
width: '100%',
source: searchViewGridDataAdapter,
theme: theme,
sortable: true,
pageable: true,
autoheight: true,
selectionmode: 'checkbox',
columns: columns
});
//hide indicator here on on success method of ajax call
};
On the click of the button call showloadelement and in the Ajax call success callback function call hideloadelement.
$("#btnSearch").bind('click', function () {
$('#divLookupSearch').jqxGrid('showloadelement');
//show indicator here
LoadLookUpSearchGrid();
}
...
success: function (data) {
$('#jqxGrid').jqxGrid('hideloadelement');
var source = data.d;
SetSearchFields($('select#ddlFilterType option:selected').text(), source);
},
...
Best Regards,
Alpesh
Oleg - are you here???
I am using jqGrid, were i set in colModel my searchoption according to the type
Like this:
var columnModel = [{ name: 'ID', index: 'ID', sortable: true,searchoptions: { sopt: ['gt']}},
{ name: 'FirstName', index: 'FirstName', sortable: true, searchoptions: { sopt: ['cn']} },
{ name: 'LastName', index: 'LastName', sortable: true ,searchoptions: { sopt: ['ge']}}
];
Now after i load the grid i want to use the fallowing code in order to add auticomplete to the search box of the grid:
for (var i = 0; i < columnModel.length; i++) {
var nameCol = columnModel[i].name;
myGrid.jqGrid('setColProp', nameCol,
{
searchoptions: {
dataInit: function (elem) {
$(elem).autocomplete({
source: function (request, response) {
autoFillSearch(request, response, $(elem).attr('name'));
},
minLength: 1
});
}
}
});
}
myGrid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true });
the autoFillSearch function is like this:
function autoFillSearch(request, response, columnToSearchName) {
var paramters = {
colName: columnToSearchName,
prefixText: request.term
};
$.ajax({
url: './ViewNQueryData.asmx/AutoCompleteSearch',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(paramters),
success: function (data) {
response($.each(data.d, function (index, value) {
return {
label: value,
value: index
}
}));
}
});
}
The problem is that new the colModels have the search option that were created the second time and dont have my specific "sopt" i want them to have....
I there any way of changing the second searchoption so that it will get the "sopt" option from the original colMadel?
Thank you in advance.
the answer for this is:
for (var i = 0; i < columnModel.length; i++) {
var nameCol = columnModel[i].name;
var soptOption = columnModel[i].searchoptions.sopt;
myGrid.jqGrid('setColProp', nameCol,
{
searchoptions: {
sopt: soptOption,
dataInit: function (elem) {
$(elem).autocomplete({
source: function (request, response) {
autoFillSearch(request, response, $(elem).attr('name'));
},
minLength: 1
});
}
}
});
}