select2 ajax dynamic search multipleselect - set values from respons on document ready - ajax

I have problem with passing data to select2 (ajax dynamic search) in edit mode on document ready.
I create test button which should add data on click and it doesnt work... Any ideas with that?
$('.select2').select2({
minimumInputLength: 3,
ajax: {
url: (...),
dataType: 'json',
data: function (params) {
return {
query: params.term
};
},
processResults: function (data, params) {
var resData = [];
data.forEach(function (value) {
if (value.name.toLowerCase().indexOf(params.term.toLowerCase()) != -1)
resData.push(value)
})
return {
results: $.map(resData, function (item) {
return {
text: item.name,
slug: item.slug,
id: item.id
}
})
};
},
},
});
$('#preselectObjectDataButton').on('click', function() {
var _array = []
var o = new Object;
o.id = 1;
o.text = "test";
o.slug = "test";
_array.push(o);
$('.select2').val(_array).trigger('change.select2');
});

Related

select2 4.0.8, templateSelection option not working

I am using select2 version 4.0.8 with ajax search. In my angular 4 application with ajax call. Till searching and populating result it works fine. But after that when I click on any option it doesn't call method specified in templateSelection option.
Below is the code I am using:
jQuery(".suggestion"+i).select2({
placeholder: 'Select Countries',
ajax: {
url: AppConstants.facebookBaseUrl + "/search",
dataType: 'json',
delay: 250,
type: "GET",
beforeSend: (request)=> {
request.setRequestHeader("Authorization", "Bearer "+this.user.facebookPage_Token);
},
data: (params)=> {
return {
q: params.term, // search term
location_types: this.facebookFilters[i].filter,
type: "adgeolocation",
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.data,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
multiple:true,
minimumInputLength: 2,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo (repo) {
if (repo.loading) {
return repo.text;
}
var $container = jQuery("<option (click)='selectCountry($event)' class='country_name' value='"+repo.key+"'>"+repo.name+"</option>");
return $container;
}
function formatRepoSelection (repo) {
var $container = jQuery("<option class='selectedCountry' value='"+repo.key+"'>"+repo.name+"</option>");
return $container;
// return repo.key || repo.text;
}
And HTML:
<select class="form-control" name="selected[]" [ngClass]="'suggestion'+i"></select>
What I am doing wrong here?
thanks in advance!
Try by changing option to span as:
function formatRepoSelection (repo) {
var $container = jQuery("<span class='selectedCountry'>"+repo.name+"</span>");
return $container;
// return repo.key || repo.text;
}

Kendo treeview HierarchicalDataSource not showing child nodes

I have a kendo Treeview which is showing the parent nodes but the child nodes are not seen. Can anyone tell me where am i going wrong. I am new to this concept. I followed the below link but its not working.
http://demos.telerik.com/kendo-ui/treeview/remote-data-binding
function treeView() {
var treeM = new kendo.data.HierarchicalDataSource({
schema: {
data: function (response) {
console.log("response" + JSON.stringify(response));
var rdata = {};
if (response.d) {
rdata = JSON.parse(response.d);
}
else {
rdata = response;
}
return rdata; // ASMX services return JSON in the following format { "d": <result> }.
},
model: {
hasChildren: true,
id: "ID",
expanded: true,
fields: {
ID: { editable: false, nullable: false, type: "string" },
LINK: { editable: true, nullable: true, type: "string" },
},
},
},
transport: {
read: {
url: "/getParent",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json"
},
parameterMap: function (data, type) {
if ((type == "update") || (type == "create") || (type == "destroy")) {
console.log('parameterMap:');
return JSON.stringify({ "LinksJson": data });
console.log(JSON.stringify(data));
} else {
return data;
}
}
}
});
$("#treeview1").kendoTreeView({
dataSource: treeM,
dataValueField: "ID",
dataTextField: ["LINK","Name"]
});
}
$("#treeview").on("click", ".k-in", function (e) {
var tree = $("#treeview").data('kendoTreeView');
tree.toggle($(e.target).closest(".k-item"));
});
$(document).ready(function () {
treeView();
});
Service:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getParent()
{
using (var context = new Data.Entities())
{
IQueryable<ERPv2.Data.Links> dataQuery = from x in context.Links
where x.ParentID == 68
select x;
var newQry = dataQuery.AsEnumerable().Select(c => new
{
ID = c.ID,
Name = c.Name,
Children = HasChildren(231)
});
JavaScriptSerializer JSON = new JavaScriptSerializer();
return JSON.Serialize(newQry);
}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool HasChildren(int ID)
{
using (var context = new Data.Entities())
{
IQueryable<ERPv2.Data.Links> dataQuery = from x in contextLinks
where x.ParentID == ID
select x;
return dataQuery.AsEnumerable().Any();
}
}
Even when you try to view the child nodes, it will try to call getLinks and not the getreports.
From what i have seen , you should have only one method for getting parent and children. Can be an array inside each parent node.
Can you combine the data from GetReports method inside getlinks itsself and give it a shot.
You should try and get this working here with hardcoded values and then do configure with services.
http://docs.telerik.com/kendo-ui/api/javascript/ui/treeview#configuration-dataSource

Results not displaying using ajax-select2 e

I have wriiten a code to display relevant serch results using select2 and ajax.The results are showing in console properly but not displayed in result table of select2.It just states no reults found...Below is my code:
<script type="text/javascript">
$(".showname").select2({
ajax: {
url:"http://hub.w.net/datatables/brand_processing",
//dataType: "json",
//delay: 250,
type:'POST',
data: function (params) {
return {
search_name: params.term // search term
//console.log(params:params);
};
},
processResults: function (data) {
// 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
console.log(data.data);
return {
data:{text:data.data,id:data.id}
};
},
cache: true
},
minimumInputLength: 1
});
</script>
Any suggestions?
try this for select2 latest version
processResults: function (data, params) {
var results = [];
if (data != null && data.length > 0) {
$.each(data, function (index, item) {
results.push({
id: item.id,
text: item.text
});
});
}
return {
results: results
};
};
for select2 3.5.2 version:
results: function (data, page) { // parse the results into the format expected by Select2.
var results = [];
if (data != null && data.length > 0) {
$.each(data, function (index, item) {
results.push({
id: item.id,
text: item.text
});
});
}
return {
results: results
};
},
cache: true
}
try this on processResults function
return {
text:data.data,
id:data.id
};

keep the Ids of selected results of Kendo UI Autocomplete in a hidden input

I wrote this code to use kendo UI autocomplete. I need to show the title of the selected result in the textbox and keep the if in some hidden input, how can I get the id. it seems the select doesn't work.
$("[data-autocomplete]").each(function () {
var luurl = $(this).attr('data-lookupurl');
var thisElemt = $(this);
$(this).kendoAutoComplete({
minLength: 3,
separator: ", ",
dataTextField: "title",
select: function (e) {
var selectedOne = this.dataItem(e.item.Index());
console.log(kendo.stringify(selectedOne));
},
dataSource: new kendo.data.DataSource({
serverFiltering: true,
serverPaging: true,
pageSize: 20,
transport: {
read: luurl,
dataType: "json",
parameterMap: function (data) {
return { title: thisElemt.val() };
},
schema: {
model: {
id: "id",
fields: {
id: { type: "id" },
title: { type: "string" }
}
}
}
}
})
});
});
There is a typo error, you should use: e.item.index() instead of e.item.Index() (index is lowercase).
So the select function would be:
select : function (e) {
var selectedOne = this.dataItem(e.item.index());
console.log(kendo.stringify(selectedOne));
},
and easier way is :
var autocomplete = $("#autoCompleteId").data("kendoAutoComplete");
console.log(autocomplete.listView._dataItems[0]);
you can access to select data item in autocomplete.listView._dataItems[0] object
you can use script
<script>
$(document).ready(function () {
$("#categories").change(function () {
var url = '#Url.Content("~/")' + "Limitations/ThanaByDistrict_SelectedState";
var ddlsource = "#categories";
var ddltarget = "#target";
$.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$(ddltarget).val(data);
});
});
});
</script>
in controller like
// Get selected combox value
public JsonResult ThanaByDistrict_SelectedState ( Guid Sel_StateName )
{
JsonResult result = new JsonResult ( );
objects temp=db . objects . Single ( m => m . ob_guid == Sel_StateName );
result . Data = temp.ob_code;
result . JsonRequestBehavior = JsonRequestBehavior . AllowGet;
return result;
}
For details you can see this LINK

MVC3 and Twitter Bootstrap TypeAhead without plugin

I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

Resources