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

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

Related

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

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

Kendo Multiselect with pre determined values

I have looked everywhere and cant seem to get this figured out. My issue..
I have 1 kendo dropdown list and 3 kendo mutliselects. each selection filters the next object. Dropdownl => MS1 => MS2 => MS3...
At times, a user may come into this page with a predetermined set of values that need to be selected in the above objects. 1 for the DD and 1+ for the MS.
I can get the dropdown to populate and have the corrected selected item. I can get the first MS to populate with the correct values but not select the values that are needed (0 values are selected) and the next 2 dont work cause i cant get past the first MS properly. I feel like I am running into some kind of sync/async issues that I cant wrap my head around.
See code below. I have included all my data sources, object setups and functions that i felt were relevant (maybe too much). The important function is prePopulateSelectedValues. this is the one that gets called to use the values to select the DD list values. I only included one of the updateLineShopGroupMS (for example) as the other update functions are basically the same. Right now I am stuck on 2 different versions of code which both provide the same results - a promise and non-promise version which you can see in prePopulateSelectedValues.
Thank you in advance
var lineShopGroupDataSource = new kendo.data.DataSource({
serverFiltering: false,
transport: {
read: {
url: "/Base/GetLineShopGroupsFilteredByLocationGroup",
type: "GET",
dataType: "json",
data: function (e) {
return {
LocationGroupId: getDropDownLists("LocationGroupId").value()
};
}
}
}
});
var locationGroupDataSource = new kendo.data.DataSource({
transport: {
read: {
type: "GET",
dataType: "json",
url: '/Base/GetLocationGroupNames',
data: function (e) {
return {
LocationGroupId: getDropDownLists("LocationGroupId").value()
};
}
}
}
});
var substationDataSource = new kendo.data.DataSource({
transport: {
read: {
type: "GET",
dataType: "json",
url: '/Base/GetSubstationFilteredByLineShopGroup',
data: function (e) {
let ids = getMultiSelect("LineShopGroup").value();
return {
LineShopIds: ids.toString()
};
}
}
}
});
var circuitDataSource = new kendo.data.DataSource({
transport: {
read: {
type: "GET",
dataType: "json",
url: '/Base/GetCircuitFilteredBySubstation',
data: function (e) {
let ids = getMultiSelect("Substation").value();
return {
SubstationIds: ids.toString()
};
}
}
}
});
function setUpCircuit() {
$("#Circuit").kendoMultiSelect({
autoBind: false,
enable: false,
placeholder: "Select Circuit(s)...",
dataTextField: "Text",
dataValueField: "Value",
dataSource: circuitDataSource,
filter: "contains",
change: function () {
getHiddenCircuitList();
}
});
}
function setUpSubstation() {
$("#Substation").kendoMultiSelect({
autoBind: false,
enable: false,
dataTextField: "Text",
dataValueField: "Value",
placeholder: "Select Substation(s)...",
dataSource: substationDataSource,
filter: "contains",
change: function () {
if (document.getElementById('Circuit')) {
updateCircuitMS();
}
getHiddenSubstationList();
}
});
}
function setUpLineShopGroup() {
$("#LineShopGroup").kendoMultiSelect({
autoBind: false,
dataTextField: "Text",
dataValueField: "Value",
headerTemplate: "<label style='padding-left: 10px;'><input type='checkbox' id='selectAllLineShopGroups'> Select All</label>",
dataSource: lineShopGroupDataSource,
placeholder: "Select Line Shop/Group...",
change: function () {
if (document.getElementById('Substation')) {
updateSubstationMS();
}
checkAllFlag("LineShopGroup");
getHiddenLineShopList();
}
});
}
function setUpLocationGroupId() {
$("#LocationGroupId").kendoDropDownList({
autoBind: true,
dataTextField: "Text",
dataValueField: "Value",
optionLabel: "Select Location Group...",
dataSource: locationGroupDataSource,
change: function () {
if (document.getElementById('LineShopGroup')) {
updateLineShopGroupMS();
}
}
});
}
function prePopulateSelectedValues(locGroupList, lineShopGroupsList, substationList, circuitList) {
if (locGroupList !== "0") {
var locGrpDD = $('#LocationGroupId').data('kendoDropDownList');
var lineShopMS;
$("#LocGroupString").val(locGroupList);
locGrpDD.value(locGroupList);
if (document.getElementById('LineShopGroupString')) {
debugger
var promise = new Promise(function (resolve, reject) {
debugger
resolve(function () {
updateLineShopGroupMS();
});
});
promise.then(function() {
//we have our result here
debugger
var lineShopMS = $('#LineShopGroup').data('kendoMultiSelect');
return lineShopMS; //return a promise here again
}).then(function(result) {
//handle the final result
debugger
$("#LineShopGroupString").val(lineShopGroupsList);
result.value([lineShopGroupsList]);
}).catch(function (reason) {
debugger
});
}
if (document.getElementById("SubstationString")) {
updateSubstationMS();
var substationMS = $('#Substation').data('kendoMultiSelect');
$("#SubstationString").val(substationList);
substationMS.value(substationList);
}
if (document.getElementById("CircuitsString")) {
updateCircuitMS();
var circuitMS = $('#Circuit').data('kendoMultiSelect');
$("#CircuitsString").val(circuitList);
substationMS.value(circuitList);
}
}
}
function updateLineShopGroupMS() {
var msObj = getMultiSelect('LineShopGroup');
var ddValue = getDropDownLists('LocationGroupId').value();
if (ddValue !== '') {
msObj.enable();
lineShopGroupDataSource.read();
}
else {
msObj.enable(false);
msObj.value([]);
}
}

jsGrid preload pages ahead

I want to load items by page since I have tables with large amount of data, but I don't want to load items for each page once the user clicks it.
Instead, I rather preload 1000 items (for example) ahead and only fetch more results if the user moves to a page I still didn't fetch the data for.
Is it possible?
I found a way to solve it.
Here is the basic logic:
Create a local data cache object that will hold arrays of results for each page.
When fetching data from the server, always return data for a few pages ahead and store them in the local cache object
Write a method for the controller.loadData that will check to see if you have the desired page results in the local cache object, if so - return that array, if not - return a promise that will fetch the results with some extra data for a few pages ahead.
An example of the local cache object snapshot:
{
"1": [{name: "ff"}, {name: "fdd"}],
"2": [{name: "fds"}, {name: "dsr"}],
"3": [{name: "drr"}, {name: "ssr"}]
}
script section
<script type="text/javascript">
$(document).ready(function () {
List();
});
function List() {
//$(function () {
loadjsgrid();
$("#jsGrid").jsGrid({
height: "auto",
width: "100%",
filtering: true,
editing: false,
sorting: true,
autoload: true,
paging: true,
pageSize: 10,
pageButtonCount: 5,
pageLoading: true,
controller: {
loadData: function (filter) {
var startIndex = (filter.pageIndex - 1) * filter.pageSize;
var d = $.Deferred();
$.ajax({
type: 'GET',
url: '#Url.Action("[ActionName]", "[Controllername]")',
data: filter,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
if (data.Message == "Failed") {
data.Result = [];
data.Count = 0;
}
console.log(data);
d.resolve(data);
}
});
return d.promise().then(function (q) {
return {
data: q.Result,
itemsCount: q.Count
}
});
}
},
},
fields: [
{ name: "rct_no", type: "text", title: 'Serial Number', autosearch: true, width: '10%' }
],
});
$("#pager").on("change", function () {
var page = parseInt($(this).val(), 10);
$("#jsGrid").jsGrid("openPage", page);
});
}
Controller section
public ActionResult getList(int pageIndex = 1, int pageSize = 10)
{
try
{
var query = #" from rd_receipt_header
var irList = DAL.db.Fetch<[className]>(pageIndex, pageSize, #"select * " + query );
var count = DAL.db.ExecuteScalar<int>("select count(*) " + query);
return Json(new { Message = "Success", Result = irList, Count = count }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex) { return Json(new { Message = "Failed", Result = ex.Message }, JsonRequestBehavior.AllowGet); }
I am using ajax to get data from server as ajax format

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

Kendo UI reload treeview

I load a complex treeview with kendo ui via ajax because I need to load the tree with one request (works fine):
$(document).ready(function() {
buildTree();
});
function buildTree(){
$.getJSON("admin_get_treedata.php", function (data) {
$("#treeview").kendoTreeView({
select: function(item) { editTreeElement(item,'tree'); },
dataSource: data
});
})
}
If I try to reload the complete tree after changing some data via ajax the new build tree does not work correct and does not update the text.
$.ajax({
type: 'POST',
url: 'ajax/ajax_update_layer.php',
data: {
layerid:id,
...
},
success: function(data){
buildTree();
}
});
What can Ido?
Thanks
Sven
try this on ajax success callback
var data = $("#treeView").data('kendoTreeView');
data.dataSource.read();
I got mine to work.
This is what I did:
Function that creates the tree view:
function CreateNotificationTree(userId)
{
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + userId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var $item = this.dataItem(e.node);
window.open($item.NotificationLink, "_self");
}
}
Modification & data source refresh:
$('#btnDelete').on('click', function()
{
var treeView = $("#treeview").data("kendoTreeView");
var userId = $('#user_id').val();
$('#treeview').find('input:checkbox:checked').each(function()
{
var li = $(this).closest(".k-item")[0];
var notificationId = treeView.dataSource.getByUid(li.getAttribute('data-uid')).ID;
if (notificationId == "undefined")
{
alert('No ID was found for one or more notifications selected. These notifications will not be deleted. Please contact IT about this issue.');
}
else
{
$.ajax(
{
url: '../api/notifications/deleteNotification?userId=' + userId + '&notificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
treeView.remove($(this).closest('.k-item'));
}
});
});
Hope that helps.

Resources