Kendo Treeview expand and checkbox not working after new value was passed in from a dropdown list - ajax

new to stackoverflow and implementing treeview. I'm having an issue where whenever I select a different value from my dropdown list that would populate my treeview the expand and checkbox is not working anymore. But the first time works.
So I have ajax call that would grab a parameter from a dropdown list to return JSON data to populate my tree. Here's my code. I've been pounding my head for this error and I've also tried some solution in the kendo ui documentation but it just doesn't work. Really need some help. Thank you!
Here's my code:
dataB1 = #Html.Raw(Json.Encode(ViewData["branchList"]));
reloadNewBranch = #Html.Raw(Json.Encode(ViewData["reloadNewBranch"]));
$('#comboNewBranch').kendoAutoComplete({
dataSource: dataB2,
placeholder: "Enter branch name...",
value: reloadNewBranch
});
//Create TreeView
function onChange(e) {
$("body").css("cursor", "progress");
$('#hiddenPackageArray').val('');
document.getElementById("textTestpassId").innerHTML = 'At least one(1) template must be selected.';
$('#treeview').empty();
$.ajax({
url: '#Url.Action("LoadOldBranchTemplates", "Home")',
data: { oldBranchName: $("#comboOldBranch").data("kendoAutoComplete").value() },
dataType: "json"
}).done(function (result, textStatus, jqXHR) {
var viewModel = new kendo.data.HierarchicalDataSource({
data: result,
schema: {
model: {
id: "Id",
hasChildren: true,
children: "Templates"
}
}
});
$("#treeview").kendoTreeView({
loadOnDemand: false,
checkboxes: {
checkChildren: true
},
check: onCheck,
dataSource: viewModel,
dataTextField: ["TestPassName", "DisplayName"]
})
// gathers IDs of checked nodes
function checkedNodeIds(nodes, checkedNodes) {
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
checkedNodes.push(nodes[i].Id);
let filtered = checkedNodes.filter(function (listOfId) {
return listOfId != null;
});
$('#hiddenPackageArray').val(filtered);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}
// show checked node IDs on datasource change
function onCheck(e) {
console.log("I'm in onSelect function");
var checkedNodes = Array();
var treeView = $("#treeview").data("kendoTreeView");
var message = String();
checkedNodeIds(treeView.dataSource.view(), checkedNodes);
console.log("Checkbox changed :: " + this.text(e.node));
if (checkedNodes.length > 0) {
message = checkedNodes.join(" ");
} else {
message = "No package(s) are selected.";
$('#hiddenPackageArray').val('');
}
$("#result").html(message);
}
$("body").css("cursor", "default");
})
.fail(function (xmlHttpRequest, textStatus, errorThrown) {
$('#mainDiv').append('<p>Status: ' + textStatus + '</p>');
$('#mainDiv').append('<p>Error: ' + errorThrown + '</p>');
$('#mainDiv').append('<p>' + xmlHttpRequest + '</p>');
});
};

Related

knockout validation for array of objects

I have an array of dynamically added objects and I want to validate this array for required fields and numeric values.
I have 3 buttons, one for adding note, another for removing note and one for saving
How to validate every object ?
.. the code:
$(function () {
var initialData = [{
Title: "",
NoteText: "",
Suggestion: "",
MediaTime: ""
}];
var CreateNewNoteModel = function (Notes) {
var self = this;
self.Notes = ko.observableArray(ko.utils.arrayMap(Notes, function (Note) {
return { Title: Note.Title, NoteText: Note.NoteText, Suggestion: Note.Suggestion, MediaTime: Note.MediaTime };};
}));
var i = 1;
self.addNote = function () {
self.Notes.push({
Title: "", NoteText: "", Suggestion: "", MediaTime: ""
});
$('#editor' + i).wysihtml5();
$('#editorB' + i).wysihtml5();
i++;
};
self.removeNote = function (Note) {
self.Notes.remove(Note);
};
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.Notes), null, 2));
var jsondata = self.lastSavedJson();
$.ajax({
url: "/api/Notes/?mid=" + m + "&p=" + p,
cache: false,
type: 'Post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: jsondata,
success: function () {
alert("Success");
document.location.reload(true);
}
});
};
self.lastSavedJson = ko.observable("")
};
ko.applyBindings(new CreateNewNoteModel(initialData));
});
I am using jQuery validate plugin to add validation to knockout-js by using jQuery's validation methods: "$.validator.addMethod" and "$.validator.addClassRules".
Example:
First define your validation methods and css classes. Later on, we add the css classes to your inputs to validate your fields.
function DefineValidationRules() {
$.validator.addMethod("validateNumber", ValidateInteger, "This field is not a number");
$.validator.addMethod("validateRequired", $.validator.methods.required, "This field is required");
$.validator.addMethod("validateMin", $.validator.methods.min, $.format("This number be greater than or equal to {0}"));
$.validator.addMethod("validateMax", $.validator.methods.min, $.format("This number must be less than or equal to {0}"));
$.validator.addMethod("validateMinlength", $.validator.methods.minlength, $.format("This field must contain at least {0} characters"));
$.validator.addMethod("validateRangelength", $.validator.methods.rangelength, $.format("This field must contain between {0} and {1} characters"));
$.validator.addClassRules("validate-number", { validateNumber: true });
$.validator.addClassRules("validate-number-min", { validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required-number-min", { validateRequired: true, validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required", { validateRequired: true });
$.validator.addClassRules("validate-rangelengthmax6", { validateRangelength: [0,6] });
}
DefineValidationRules();
You can also add your own custom validation method:
function ValidateInteger(value) {
//do whatever you want to check
}
Having an input in knockout:
<input class="validate-required validate-number" type="text" data-bind="value: examplefield, valueUpdate: 'afterkeydown', attr: { attrname: 'itsvalue'}" />
Checking on submit:
$("#yoursubmitbutton").on("click", function () {
var formtosubmit = $("#idofyourform");
//check for validation errors
if (isValid(formtosubmit)) {
formtosubmit.submit();
//
// code to proceed to next step
}
});
function isValid(el) {
var $thisform = el;
$thisform.validate({
errorElement: "label",
errorPlacement: function (error, element) {
//eventual different error placing
if (element.attr("name") == "fname" || element.attr("name") == "lname") {
element.css("border", "2px solid red");
error.insertAfter("#lastname");
} else {
error.insertAfter(element);
}
}
});
return $thisform.valid();
}

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.

JQgrid custom button to display additional record details as in view record dialog

Here is my code for custom button, i would like to display additional details about the selected row from server side to jqgrid dialog box with similar look and feel of view record dialog. Can someone help with a sample code to create a dialog box similar to view record from custom button onclick?
jQuery("#list2").jqGrid('navButtonAdd','#pager2',{
caption:"", title: "History",buttonicon:"ui-icon-clock",
onClickButton : function () {
var grid = $("#list2");
var rowid = grid.jqGrid('getGridParam', 'selrow');
if (rowid) {
var alertIDs = {themodal:'alertmod',modalhead:'alerthd',modalcontent:'alertcnt'};
//if ($("#"+alertIDs.themodal).html() === null) {
//alert("1");
$.jgrid.createModal(alertIDs," <span tabindex='0'><span tabindex='-1' id='jqg_alrt' class='ui-jqgrid'></span></span>",
{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqModal:true,drag:true,resize:true,
caption:"History",
top:300,left:500,width:'auto',height: 'auto',closeOnEscape:true,
zIndex: null},"","",true);
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqm:true});
$("#jqg_alrt").focus();
$("#jqg_alrt").load('jsontableHeadingsApartmentResource.action?viewBy=' + viewBy+'&timeZone=' + timeZone);
} else {
var alertIDs = {themodal:'alertmod',modalhead:'alerthd',modalcontent:'alertcnt'};
$.jgrid.createModal(alertIDs,"<div>"+$.jgrid.nav.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",
{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqModal:true,drag:true,resize:true,
caption:$.jgrid.nav.alertcap,
top:300,left:500,width:200,height: 'auto',closeOnEscape:true,
zIndex: null},"","",true);
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqm:true});
$("#jqg_alrt").focus();
}
}
});
Found the solution.
Here is the updated working code, i had to use jgrid info_dialog,
jQuery("#list2").jqGrid('navButtonAdd','#pager2',{
caption:"", title: "History",buttonicon:"ui-icon-clock",
onClickButton : function () {
var grid = $("#list2");
var rowid = grid.jqGrid('getGridParam', 'selrow');
var msg = "" ;
if (rowid) {
$.ajax({
url: 'jsontableHistoryApartmentResource.action?viewBy=' + viewBy+'&rowId=' + rowid,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, st) {
if (st == "success") {
msg = data.rr.history;//jqgrid history data
$.jgrid.info_dialog('History','<span style="white-space: nowrap">' + msg +'</span>', $.jgrid.edit.bClose,{buttonalign:'center', width:'auto',resize: true , align: 'left'});
}
},
error: function () {
// alert("Error with AJAX callback");
}
});
} else {
var alertIDs = {themodal:'alertmod',modalhead:'alerthd',modalcontent:'alertcnt'};
$.jgrid.createModal(alertIDs,"<div>"+$.jgrid.nav.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",
{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqModal:true,drag:true,resize:true,
caption:$.jgrid.nav.alertcap,
top:300,left:500,width:200,height: 'auto',closeOnEscape:true,
zIndex: null},"","",true);
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID(this.p.id),jqm:true});
$("#jqg_alrt").focus();
}
}
});

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

JSON, jQueryUI Autocomplete, AJAX - Cannot get data when array is not local

I have searched stackoverflow, as well as the web for some insight into how to get the jQueryUI Autocomplete plugin working with my JSON data, and I'm at a loss. I had it working like a charm with a local data array. I was able to pull values and build html.
I ran into a problem when I had to pull JSON form this source:
/Search/AjaxFindPeopleProperties2
?txtSearch=ca pulls up the test data that I am trying to loop through, when I type in 'ca' to populate the autocomplete list. One of the problems is that ?term=ca is appended to the url instead of ?txtSearch=ca and I'm not sure how to change it.
This is an example of the data:
{
"MatchedProperties": [
{
"Id": 201,
"Name": "Carlyle Center",
"Description": "Comfort, convenience and style are just a few of the features you'll ...",
"ImageUrl": "/Photos/n/225/4989/PU__ThumbnailRS.jpg"
}
]
}
...and here is the ajax call I'm trying to implement:
$(document).ready(function () {
val = $("#txtSearch").val();
$.ajax({
type: "POST",
url: "/Search/AjaxFindPeopleProperties2",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#txtSearch').autocomplete({
minLength: 0,
source: data.d, //not sure what this is or if it's correct
focus: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
$.widget("custom.catcomplete", $.ui.autocomplete, {
//customize menu item html here
_renderItem: function (ul, item) {
return $("<li class='suggested-search-item" + " " + currentCategory + "'></li>")
.data("item.autocomplete", item)
.append($("<a><img src='" + item.MatchedProperties.ImageUrl + "' /><span class='name'>" + item.MatchedProperties.Name + "</span><span class='location'>" + "item.location" + "</span><span class='description'>" + item.MatchedProperties.Description + "</span></a>"))
.appendTo(ul);
},
_renderMenu: function (ul, items) {
var self = this,
currentCategory = "Properties Static Test Category";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='suggested-search-category ui-autocomplete-category'>" + currentCategory + "</li>");
//currentCategory = item.category;
}
self._renderItem(ul, item);
});
}
}//END: widget
//return false;
},
select: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
//$('#selectedValue').text("Selected value:" + ui.item.Abbreviation);
return false;
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
}); //END ajax
}); //END: doc ready
and I'm initializing here:
<script type="text/javascript">
//initialize autocomplete
$("#txtSearch").autocomplete({ //autocomplete with category support
/*basic settings*/
delay: 0,
source: "/Search/AjaxFindPeopleProperties2",
autoFocus: true,
minLength: 2 //can adjust this to determine how many characters need to be entered before autocomplete will kick in
});
//set auto fucus
$("#txtSearch").autocomplete("option", "autoFocus", true);
</script>
any help would be great...
Thanks!

Resources