Jquery autocomplete Select not working - jquery-ui

i want to select the Autocomplete box item list . but it is not working . i have write this code to get the item. whenever i use self._renderItemData = function (ul, item) this function customized way the selection stops and when i comment this function my code works fine . please help me to know where am i wrong. i have used jquery ui 1.9 to write the code.
$(document).ready(function () {
var term = "";
var type = "";
var key = "";
$("#searchTextBox").autocomplete({
minLength: 2,
autoFocus: true,
source: function (request, response) {
$.ajax({
url: "../CustomHandlers/SearchHandler.ashx",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: { term: request.term },
success: function (data) {
if (!data || data.length == 0) {
response([{
label: "noMatched",
hcount:0,
type: "noResult",
key: "noResult"
}]);
}
else {
response($.map(data, function(item) {
return {
label: item.label,
hcount:item.record,
type: item.type,
key: item.key
}
}))
}
}
});
$.ui.autocomplete.prototype._renderMenu=function (ul, items) {
var self = this;
currentType = "";
$.each(items, function (index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>" + item.type + "</li>");
currentType = item.type;
}
self._renderItemData(ul, item);
});
self._renderItemData = function (ul, item) {
var searchhtml = "<a class='autocomplitList'>" + item.label + "<span>" + "(" + item.hcount + ") " + "</span>" + "</a>";
return $("<li></li>")
.data("item.autocomplete", item)
.append(searchhtml)
.appendTo(ul);
};
}
}
, select: function (event, ui)
{
term = ui.item.label;
type = ui.item.type;
key = ui.item.key;
// ui.item.option.selected = true;
// $("#searchTextBox").val(ui.item.label);
// return false;
//var selectedObj = ui.item.key;
// alert("Selected: " + selectedObj);
}
,open: function (event, ui) {
//event.addClass("nodis");
}
,close: function () {
// event.removeClass("nodis")
this._trigger("close");
}
});

Try this
$(document).ready(function() {
var term = "";
var type = "";
var key = "";
$.ui.autocomplete.prototype._renderMenu = function(ul, items) {
var self = this;
currentType = "";
$.each(items, function(index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>"
+ item.type + "</li>");
currentType = item.type;
}
self._renderItemData(ul, item);
});
self._renderItemData = function(ul, item) {
var searchhtml = "<a class='autocomplitList'>" + item.label
+ "<span>" + "(" + item.hcount + ") " + "</span>" + "</a>";
return $("<li></li>").data("item.autocomplete", item)
.append(searchhtml).appendTo(ul);
};
}
$("#searchTextBox").autocomplete({
minLength : 2,
autoFocus : true,
source : function(request, response) {
response([{
label : "Value 1",
hcount : 0,
type : "t1",
key : "v1"
}, {
label : "Value 2",
hcount : 0,
type : "t1",
key : "v2"
}, {
label : "Value 3",
hcount : 0,
type : "t2",
key : "v3"
}, {
label : "Value 4",
hcount : 0,
type : "t3",
key : "v4"
}]);
}
,
select : function(event, ui) {
term = ui.item.label;
type = ui.item.type;
key = ui.item.key;
// ui.item.option.selected = true;
// $("#searchTextBox").val(ui.item.label);
// return false;
// var selectedObj = ui.item.key;
// alert("Selected: " + selectedObj);
},
open : function(event, ui) {
// event.addClass("nodis");
},
close : function() {
// event.removeClass("nodis")
this._trigger("close");
}
});
$("#searchTextBox").data('autocomplete')._renderMenu = function(ul, items) {
var that = this;
var currentType = "";
$.each(items, function(index, item) {
if (item.type != currentType) {
ul.append("<li class='ui-autocomplete-type'>"
+ item.type + "</li>");
currentType = item.type;
}
$("<li></li>").addClass('newp').append($("<a></a>")
.text(item.label)).appendTo(ul).data(
"ui-autocomplete-item", item);;
});
}
});
Demo: Fiddle

Related

Autocomplete not showing suggestion list when triggered second time

I have autocomplete with two sources. When an item is selected after search from first source, if certain conditions are met, the second search is forced. This brings back results - I can see them writing into console but the list of suggestions will not show up unless "keypress" is made. I tried to automate this with forcing the .ui-list to show and with forcing "keypress" events but to no avail... has anybody got any experience and advice on this? Thanks.
$(document).ready(function () {
var stopSearch = false;
var sel = "";
var finished = false;
$('#txtLiveDept').autocomplete({
source: function (request, response) {
console.log("stopSearch" + stopSearch);
if (stopSearch == false) {
console.log("first ajax");
$.ajax({
url: '/en-gb/LiveDepartures/CombinedAjax',
data: "{ inputTerm: '" + request.term + "'}",
//dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
autoFocus: true,
success: function (data) {
console.log(data.Locations);
console.log(data.ServiceResponses);
if (data)
var resp1 = data.Locations;
var resp2 = data.ServiceResponses;
var dataF = resp2.concat(resp1);
console.log(dataF);
response($.map(dataF, function (item) {
console.log("item" + item.FullText);
var label = "";
if (item.FullText == undefined) {
label = item.ServiceNumber + ", " + item.Description;
}
else {
label = item.FullText;
}
return {
Label: label,
FullText: item.FullText,
Category: item.Category,
Latitude: item.Latitude,
Longitude: item.Longitude,
value: label,
StopLabel: item.StopLabel,
ServiceId: item.ServiceId
}
}));
failure: function err(response) {
console.log("error: " + response.d);
}
},
});
}
else if (stopSearch == true) {
console.log("second ajax");
$.ajax({
url: '/en-gb/LiveDepartures/GetStops',
data: "{ serviceId: '" + sel + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
autoFocus: true,
success: function (data) {
if (data) {
response($.map(data, function (item) {
console.log("item" + item.Name + item.StopLabel);
$("#txtLiveDept").val("");
$(".ui-menu").show();
console.log("just before");
return {
label: item.Name + ", " + item.StopLabel,
FullText: item.FullText,
Category: item.Category,
Latitude: item.Latitude,
Longitude: item.Longitude,
value: item.Name + ", " + item.StopLabel,
StopLabel: item.StopLabel,
ServiceId: item.ServiceId
};
}));
}
},
});
}
},
select: function (e, selected) {
console.log("selected:" + selected.item.ServiceId);
if (selected.item.ServiceId != undefined) {
console.log("in third");
sel = selected.item.ServiceId;
var item = selected.item.ServiceId;
console.log("third item" + item);
stopSearch = true;
console.log("finished" + finished);
if (finished == false) {
$("#txtLiveDept").autocomplete("search", item);
}
else {
alert("hey");
}
}
},
minLength: 0
});
});
Please consider the following code.
$(function() {
var stopSearch = false;
var sel = "";
var finished = false;
function getCombined(q) {
var results;
$.ajax({
url: '/en-gb/LiveDepartures/CombinedAjax',
data: {
inputTerm: q
},
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log(data.Locations);
console.log(data.ServiceResponses);
if (data.length) {
var dataF = data.Locations.concat(data.ServiceResponses);
console.log(dataF);
results = $.map(dataF, function(item) {
console.log("item" + item.FullText);
var label = "";
if (item.FullText == undefined) {
label = item.ServiceNumber + ", " + item.Description;
} else {
label = item.FullText;
}
return {
Label: label,
FullText: item.FullText,
Category: item.Category,
Latitude: item.Latitude,
Longitude: item.Longitude,
value: label,
StopLabel: item.StopLabel,
ServiceId: item.ServiceId
}
});
}
},
failure: function err(response) {
console.log("error: " + response.d);
}
});
return results;
}
function getStops(q) {
var results;
$.ajax({
url: '/en-gb/LiveDepartures/GetStops',
data: {
serviceId: q
},
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data.length) {
results = $.map(data, function(item) {
console.log("item" + item.Name + item.StopLabel);
$("#txtLiveDept").val("");
$(".ui-menu").show();
console.log("just before");
return {
label: item.Name + ", " + item.StopLabel,
FullText: item.FullText,
Category: item.Category,
Latitude: item.Latitude,
Longitude: item.Longitude,
value: item.Name + ", " + item.StopLabel,
StopLabel: item.StopLabel,
ServiceId: item.ServiceId
};
});
}
}
});
return results;
}
$('#txtLiveDept').autocomplete({
autoFocus: true,
source: function(request, response) {
console.log("stopSearch", stopSearch);
if (stopSearch) {
console.log("second ajax");
response(getStops(sel));
} else {
console.log("first ajax");
response(getCombined(request.term));
}
},
select: function(e, selected) {
console.log("selected:" + selected.item.ServiceId);
if (selected.item.ServiceId != undefined) {
console.log("in third");
sel = selected.item.ServiceId;
var item = selected.item.ServiceId;
console.log("third item" + item);
stopSearch = true;
console.log("finished" + finished);
if (finished == false) {
$("#txtLiveDept").autocomplete("search", item);
} else {
alert("hey");
}
}
return false;
},
minLength: 0
});
$('#txtLiveDept').focus(function(){
$(this).autocomplete("search");
});
});

Kendo UI Treelist rows disappears after editing

I use Kendo UI in ASP .NET MVC app. I have Kendo Treelist. Sometimes, after editing a row, all rows disappear, and I see only root element without child rows. Is it Kendo bug?Or I can prevent it? And when rows have disappeared, I refresh page, do the same changes and save treelist - the treelist works correctly.
var parsedXmlDataInJson = #Html.Raw(#ViewBag.XmlData); //jsonarray data
$( document ).ready(function() {
});
function ShowMessage(message,timeout) //пока сообщению пользователю в левом верхнем углу
{
var divMessage = $('#toggler');
if(divMessage.css('display') != 'none')
{
divMessage.clearQueue();
divMessage.stop();
divMessage.css('display','none');
}
if (timeout == 0)
divMessage.text(message).toggle('slow');
else
divMessage.text(message).toggle('slow').delay(timeout).toggle('slow');
}
var treelistds = new kendo.data.TreeListDataSource({ //CRUD for dataSource
transport: {
read: function(e) {
e.success(parsedXmlDataInJson);
},
update: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
value = updatedItem;
return false;
}
});
e.success();
},
create: function(e) {//Works for root element when editing only once - it's broke my treelist.
e.data.Id = GetId();
parsedXmlDataInJson.push(e.data);
e.success(e.data);
},
destroy: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
parsedXmlDataInJson.splice(indx, 1);
}
});
e.success();
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: false,
schema: {
model: {
id: "Id",
parentId: "parentId",
fields: {
Id: {
type: "number",
editable: true,
nullable: false
},
parentId: {
field: "parentId",
nullable: true
}
}
}
}
});
$("#treeList").kendoTreeList({
resizable: true,
dataSource: treelistds,
toolbar: ["create"],
columns: [{
field: "typeAndAttributes",
width:400
}, {
field: "text",
title: "Текст",
}, {
field: "cData",
title: "CDATA",
}, { //my custom command
command: ["edit", "destroy", "createchild", {
name: "commentOut",
text: "commentOut",
click: function(e) {
var dataItem = this.dataItem($(e.target).closest("tr")); ///my custom command
dataItem.commentedOut = !dataItem.commentedOut;
var isCommentedOut = dataItem.commentedOut;
var childNotes = this.dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) //
{
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
//обновляем цвет и текст кнопок у всех элементов вызывая dataBound
$("#treeList").data("kendoTreeList").refresh();
},
}, ]
}],
messages: {
commands: {
edit: "Изменить",
destroy: "Удалить",
createchild: "Добавить"
}
},
dataBound: function(e) {
this.autoFitColumn(3);
Databound(e.sender, e.sender.table.find("tr"));
},
editable: true,
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html()),
window: {
width:800
}
},
edit: function(e) { //invokes when popup open
$("#date").kendoDateTimePicker({
});
$("#cDataEditor").kendoEditor({
tools: [
"formatting", "bold", "italic", "underline", "insertUnorderedList",
"insertOrderedList", "indent", "outdent", "createLink", "unlink"
],
resizable: {
content: true,
toolbar: true,
max:350
}
});
//my custom logic. Popup contains many fileds splitted from one model field
if (!e.model.isNew()) { //split typeAndAttrubites to popup's fileds
var fileds = e.model.typeAndAttributes.split(';').
filter(function(v) {
return v !== ''
});
e.container.find("#type").val(fileds[0]);
var length = fileds.length;
for (i = 1; i < length; i++) {
var keyAndValue = fileds[i].split('=');
if (keyAndValue[0] != "id")
e.container.find("#" + keyAndValue[0].trim()).val(keyAndValue[1].trim());
else
e.container.find("#xmlId").val(keyAndValue[1].trim());
}
}
},
save: function(e) { //invokes when saving
var splitter = "; ";
var inputValue = $("input[id='type']").val().trim();
if (e.model.type !== undefined) {
e.model.typeAndAttributes = e.model.type;
} else {
e.model.typeAndAttributes = inputValue;
}
var allInputs = $(":input[data-appointment=attributes]");
allInputs.each(function(index, input) { //collect inputs in one filed
var attrName;
var attrValue;
if (input.id != "id") {
attrName = input.id;
e.model[attrName];
} else {
attrName = "id";
attrValue = e.model["xmlId"];
}
//значение изменили и оно не пустое
if (attrValue !== undefined && attrValue !== "") {
if (attrValue == false)
return true;
e.model.typeAndAttributes += splitter + attrName + "=" + attrValue;
}
//my custom logic
else if (input.value.trim() && input.value != "on") {
e.model.typeAndAttributes += splitter + attrName + "=" + input.value.trim();
}
})
}
});
//рекурсивно помечаем ряды как закомментированные или нет
function SetChildrenIsCommentedOut(dataItem, isCommentedOut) {
var childNotes = $("#treeList").data("kendoTreeList").dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) {
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
}
//Раскрашивает строки соответственно значению закомментировано или нет
function Databound(sender, rows) {
rows.each(function(idx, row) {
var dataItem = sender.dataItem(row);
if (dataItem.commentedOut) {
//обозначаем ряд как закомментированный
$(row).css("background", "#DCFFE0");
$(row).find("[data-command='commentout']").html("Раскомментировать");
} else {
//обозначаем ряд как незакомментированный
$(row).css("background", "");
$(row).find("[data-command='commentout']").html("Закомментировать");
}
})
}
});
var currentId = 0;
function GetId() { //генерирование Id для новых записей
var dataSource = $("#treeList").data("kendoTreeList").dataSource;
do {
currentId++;
var dataItem = dataSource.get(currentId);
} while (dataItem !== undefined)
return currentId;
}

IE 11 changing URL

I am getting strange behaviour in IE 11.
When I go to my web application using URL
"hostname:port/myapp-web/app/login.jsp"
The login page is displayed, And Login is done successfully.
Now. Problem is that, after logging in, App's landing page is index.html.
So URL should be "hostname:port/myapp-web/app/index.html"
Instead, IE changes it to "hostname:port///index.html"
Now, when I try to do any other operation or navigation, it fails because base URL is changed and my JS code cannot find app context root and all AJAX calls fails.
I tried searching over internet for the same, but couldn;t find any answer.
Please help if anyone has idea about such behaviour.
P.S. App is working fine in IE: 8/9, Chrome and FF.
I found something related to UTF-* character URLs but my app uses plain text URL with NO special characters.
App is developed using Spring for server side and KnockoutJS, HTML for UI.
Thanks in advance for the help.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=EDGE" />
<!-- script includes -->
</head>
<body>
<!-- NavigationBar -->
</body>
<script type="text/javascript">
app.initialize(); // app.js
$.getJSON('/myapp-web/Security/authorise', function (response) {
app.common.navbar.reRenderNavBar(response);
app.navigation = new Navigation("AdminHome"); // navigation.js
// This navigation causes IE11 to change URL to http://host:port///#AdminHome
// it should be // http://host:port/myapp-web/app/index.html#AdminHome
});
</script>
</html>
Navigation.js
var ua = window.navigator.userAgent
var msie = ua.indexOf("MSIE ")
var ieVer = -1;
if (msie > 0) {
var ieVer = ua.substring(msie + 5, ua.indexOf(".", msie));
//console.log(ieVer);
}
var NavigationInput = function (pName, pValue) {
this.paramName = pName;
this.paramValue = pValue;
this.toString = function () {
return pName + ":" + pValue;
}
}
var Navigation = function (startupView) {
var self = this;
this.navInput = [];
this.navViewModel = null;
this.navViewModelInitComplete = false;
// this.navigate = function navigate(view) {
//
// if (view !== this.currentView) {
// self.loadView(view, true, null);
// }
// }
this.navigateWithParams = function navigateWithParams(view, params) {
self.loadView(view, true, params);
}
this.goBack = function goBack() {
history.go(-1);
//history.back();
}
this.loadView = function (view, pushHistory, params) {
var contentframe = $("#content");
//app.consolePrintInfo("navigation", "previous view: " + self.currentView + " new view: " + view);
if (typeof (self.currentView) != 'undefined' && self.currentView
&& self.currentView.toLowerCase() == view.toLowerCase()
&& isParamsEqual(params)) {
return;
}
var constructedView;
constructedView = "Views/" + view + "/" + view + ".html"
contentframe.load(constructedView, function () {
self.currentView = view;
modUrl = view;
if (params != null) {
if (params instanceof String) {
modUrl = params;
}
else {
var queryStr = self.convertParamsToQueryString(params);
modUrl += "?" + queryStr;
}
// if (typeof(app.navigation.navViewModel) != 'undefined'
// && app.navigation.navViewModel
// && !app.navigation.navViewModelInitComplete)
// {
// app.navigation.navViewModelInitComplete = app.navigation.navViewModel.initViewModel(self.convertQueryStringToParams(modUrl));
// }
}
if (pushHistory) {
if (ieVer > 6) {
window.history.pushState(view, null, modUrl);
}
else {
window.history.pushState(view, null, "#" + modUrl);
}
}
app.consolePrintInfo("navigation", "modified url:" + modUrl + " view model: " + app.navigation.navViewModel);
var navInputs = self.convertQueryStringToParams(modUrl);
self.urlInputs = navInputs;
app.navigation.navViewModelInitComplete = app.navigation.navViewModel.initViewModel(navInputs);
//$.getScript("Views/" + view + ".js", function () {
//});
});
isParamsEqual = function (iParams) {
if ((typeof(self.urlInputs) == 'undefined' || !self.urlInputs)
&& (typeof(iParams) == 'undefined' || !iParams)) {
return true;
}
else if (app.utility.isObjectNull(self.urlInputs) && app.utility.isObjectNull(iParams)) {
return true;
}
else {
return false;
}
}
}
this.convertParamsToQueryString = function (params) {
var result = "";
for (var i = 0; i < params.length; i++) {
if (i > 0) {
result += "&";
}
result += params[i].paramName + "=" +
params[i].paramValue;
}
return result;
};
this.convertQueryStringToParams = function (modUrl) {
var inputs = null;
var fragments = modUrl.split("?");
if (fragments && fragments.length == 2) {
var f = fragments[1].split("&");
if (f && f.length > 0) {
for (var i = 0; i < f.length; i++) {
var inp = f[i].split("=");
if (inputs == null) inputs = [];
inputs.push(new NavigationInput(inp[0], inp[1]));
}
}
}
return inputs;
};
this.back = function () {
if (history.state) {
var view = self.getView();
self.loadView(view, false, self.convertQueryStringToParams(location.href));
} else {
var view = self.getView();
self.loadView(view, true, self.convertQueryStringToParams(location.href));
}
};
this.getView = function () {
var fragments = location.href.split('#');
if (fragments && fragments.length === 2) {
var inFrag = fragments[1].split('?');
if (inFrag && inFrag.length === 2) {
return inFrag[0];
}
else {
return fragments[1];
}
} else {
return startupView;
}
};
this.loadView(this.getView(), true, this.convertQueryStringToParams(location.href));
$(window).on('popstate', self.back);
}
app.js:
-----------------
app = {};
// utilities
app.utility = {};
app.ui = {};
// common
app.common = {};
// validation
app.validation = {};
// common components
app.common.navbar = {};
app.common.authorisation = {};
app.initialize = function () {
$.blockUI.defaults.message = '<h4><img src="images/busy.gif" /> Processing...</h4>';
$.blockUI.defaults.css.border = '2px solid #e3e3e3';
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
//$(document).click(function() { $(".popover").remove(); });
}
app.consolePrintInfo = function (tag, message) {
if (typeof(console) != 'undefined' && console)
console.info(tag + ": " + message);
}
app.ui.showAppError = function (message) {
app.consolePrintInfo("App", "displaying error message: " + message);
$('#error-console').removeClass('app-error-console-hidden');
$('#error-console').removeClass('alert-info');
$('#error-console').addClass('alert-error');
$('#error-console').html(message);
}
app.ui.showAppInfo = function (message) {
app.consolePrintInfo("App", "displaying info message: " + message);
$('#error-console').show();
$('#error-console').removeClass('app-error-console-hidden');
$('#error-console').removeClass('alert-error');
$('#error-console').addClass('alert-info');
$('#error-console').html(message);
$('#error-console').fadeOut(4000);
}
app.utility.addQueryParameter = function (url, paramName, paramValue) {
var rUrl = url;
if (typeof(paramName) != 'undefined' && paramName
&& typeof(paramValue) != 'undefined' && paramValue) {
if (rUrl.indexOf("?") != -1) {
rUrl = rUrl + "&" + paramName + "=" + paramValue;
}
else {
rUrl = rUrl + "?" + paramName + "=" + paramValue;
}
}
return rUrl;
}
app.utility.addSearchParameter = function (paramName, paramValue) {
var rValue = undefined;
if (typeof(paramName) != 'undefined' && paramName
&& typeof(paramValue) != 'undefined' && paramValue) {
rValue = paramName + ":" + paramValue;
}
return rValue;
}
app.utility.searchParameter = function (inputKeyArray, paramName) {
if (inputKeyArray instanceof Array) {
for (var i = 0; i < inputKeyArray.length; i++) {
if (inputKeyArray[i].paramName == paramName) {
return inputKeyArray[i].paramValue;
}
}
}
return undefined;
}
app.utility.isObjectNull = function (obj) {
return typeof(obj) == 'undefined' || obj == undefined || !obj;
}
app.utility.isObjectNotNull = function (obj) {
return typeof(obj) != 'undefined' && obj;
}
app.utility.isFunction = function (obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
app.utility.parseError = function (em) {
if (!app.utility.isObjectNull(em)) {
jem = JSON.parse(em);
var keyArray = new Array();
keyArray.push(jem.errorCode);
keyArray.push(jem.errorMessage);
return keyArray;
}
else {
return undefined;
}
}
app.utility.showAppErrorDialog = function (errTitle, errMessage) {
if (!app.utility.isObjectNull(errMessage)) {
var $message = $("Error:" + errMessage)
.dialog({autoOpen: false, width: 300, title: errTitle, modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.showErrorDialog = function (err) {
if (!app.utility.isObjectNull(err)) {
var $message = $('<div><p>Unfortunately, there has been error in the server!</p><p>' + err[1] + '</p><p>Please send the screenshot to developer team</div>')
.dialog({autoOpen: false, width: 300, title: err[0], modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.showDialog = function (heading, text) {
if (!app.utility.isObjectNull(heading) && !app.utility.isObjectNull(text)) {
var $message = $('<div><p>' + text + '</p></div>')
.dialog({autoOpen: false, width: 300, title: heading, modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
}
app.utility.populateToolTip = function () {
$("img[id^='tooltip']").each(function () {
var idName = $(this).attr("id");
$('#' + idName).tooltip('toggle');
$('#' + idName).tooltip('hide');
});
};
app.utility.isNotEmptyNumberValue = function (input) {
if (app.utility.isObjectNull(input)) {
return true;
}
if (!isNaN(input) && isFinite(input) && ("" + input).indexOf("-") == -1 && ("" + input).indexOf("e") == -1) {
return true;
}
return false;
};
app.utility.isNotEmptyWholeNumberValue = function (input) {
if (app.utility.isObjectNull(input)) {
return true;
}
if (!isNaN(input) && isFinite(input) &&
("" + input).indexOf("-") == -1 && ("" + input).indexOf(".") == -1 && ("" + input).indexOf("e") == -1) {
return true;
}
return false;
};
app.utility.isNumberValue = function (input) {
if (!isNaN(input) && isFinite(input)) {
return true;
}
return false;
};
app.utility.doHttpRequest = function (input) {
if (app.utility.isObjectNull(input) || app.utility.isObjectNull(input.rURL)) {
app.utility.showDialog("Error!", "Unable to find required inputs. Error in sending request");
return false;
}
app.consolePrintInfo("HTTP REQUEST: ", "[URL] :" + input.rURL);
app.consolePrintInfo("HTTP REQUEST: ", "[Type] :" + input.rType);
app.consolePrintInfo("HTTP REQUEST: ", "[Input] :" + input.rDataToSend);
$.ajax({
url: input.rURL,
type: input.rType,
contentType: 'application/json',
cache: false,
data: input.rDataToSend,
dataType: 'json'
}).success(function (response) {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - success] :" + JSON.stringify(response));
if (!app.utility.isObjectNull(input.rOnSuccessFunction)) {
input.rOnSuccessFunction(response);
}
else if (!app.utility.isObjectNull(input.rOnSuccessMessage)) {
app.utility.showDialog("Complete", input.rOnSuccessMessage);
}
}).error(function (response) {
if (response.status == 401) {
// session expired. redirect to login page.
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] : Session Expired");
var $message = $('<div><p>' + response.responseText + '</p></div>')
.dialog({autoOpen: false, width: 300, title: 'Session Expired', modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
// Remove the cached data
//comp_storage.remove("lastStoredValue");
//comp_storage.remove("permissionStr");
//window.open("/aid-web/logout", "_self");
app.utility.doLogout();
}
}}
);
$message.dialog('open');
}
else if (response.status == 400) {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] : Server Error");
var $message = $('<div><p>' + response.responseText + '</p></div>')
.dialog({autoOpen: false, width: 300, title: 'Server Error', modal: true, buttons: {
Ok: function () {
$(this).dialog("close");
}
}}
);
$message.dialog('open');
}
else {
app.consolePrintInfo("HTTP REQUEST: ", "[Output - failure] :" + response.responseText);
if (!app.utility.isObjectNull(input.rOnErrorFunction)) {
input.rOnErrorFunction(response.responseText);
}
else if (!app.utility.isObjectNull(input.rOnErrorMessage)) {
app.utility.showDialog("Error", input.rOnErrorMessage);
}
}
});
};
app.utility.doLogout = function () {
comp_storage.remove("lastStoredValue");
comp_storage.remove("permissionStr");
window.open("/aid-web/logout", "_self");
};
// common
// Nav bar component
app.common.navbar.reRenderNavBar = function (content) {
// [SAMPLE] To update the common component. create a view model of that
// component. set the needed variables.
// and *definately call applyBindings()*
app.common.navbar.navBarViewModel = new ko.navBarComponent.viewModel({
// set compt. values if needed. like below.
//navBarComponent_isEmpty:ko.observable(false)
});
app.common.navbar.navBarViewModel.navBarComponent_reRender(content);
ko.applyBindings(app.common.navbar.navBarViewModel, $('#nav-bar').get(0));
}
// Authorisation component
app.common.authorisation.storeRoleInfo = function (permissionArr) {
comp_auth.storeRoleInfo(permissionArr);
};
app.common.authorisation.isRolePresent = function (roleName) {
return comp_auth.isRolePresent(roleName);
};
// validation
app.validation.highlightElement = function (id, text) {
}
app.validation.highlightError = function (eleId, heading, text) {
if (!app.utility.isObjectNull(heading) && !app.utility.isObjectNull(text) && !app.utility.isObjectNull(eleId)) {
$("#" + eleId).addClass("ui-state-error");
var $message = $('<div><p>' + text + '</p></div>')
.dialog({
autoOpen: true,
width: 300,
title: heading, modal: true,
close: function () {
setTimeout(function () {
jQuery("#" + eleId).removeClass("ui-state-error");
}, 500);
},
buttons: {
Ok: function () {
$(this).dialog("close");
setTimeout(function () {
jQuery("#" + eleId).removeClass("ui-state-error");
}, 500);
}
},
overlay: {
opacity: 0.1,
},
}
).parent().addClass("ui-state-error");
}
}

How to Pass Value from Control to View Json

I am a beginner in ASP.NET MVC. Here is my code, I'm looking for expert help.
In this code i am calculating SaleTotal
[HttpPost]
public double SaleTotal(DateTime? FromDate, DateTime? ToDate)
{
var Sales = from s in db.SalesMasters
where (s.BillDate >= FromDate && s.BillDate <= ToDate)
select s.STotal;
var SalesReturn = from s in db.SReturnMasters
where s.ReturnDate >= FromDate && s.ReturnDate <= ToDate
select s.SRTotal;
double TotalSales = Sales.Sum().GetValueOrDefault();
double TotalSalesReturn = SalesReturn.Sum().GetValueOrDefault();
double Balance = TotalSales - TotalSalesReturn;
return Balance;
}
public ActionResult AllSaleReport(JQueryDataTableParamModel param, int? BillNo , DateTime ? FromDate,DateTime? ToDate)
{
double SalesTotal=SaleTotal(FromDate, ToDate);
var Sales = (from S in db.SalesMasters
where (S.BillDate >= FromDate && S.BillDate <= ToDate )
select S).ToList();
var filteredSales=(from S in db.SalesMasters
where (S.BillDate >= FromDate && S.BillDate <= ToDate && S.CancelFlag==false )
select S).ToList();
var result = from S in filteredSales.Skip(param.iDisplayStart).Take(param.iDisplayLength)
select new[] { S.BillDate.GetValueOrDefault().ToString("dd-MMM-yyyy"), Convert.ToString(S.BillNo), S.RefName, S.Paymode, Convert.ToString(S.NetAmt) };
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = Sales.Count,
iTotalDisplayRecords = filteredSales.Count,
aaData = result,
SalesReturn = SaleTotal(FromDate, ToDate)
},
JsonRequestBehavior.AllowGet);
}
My JavaScript to load data to DataTable
function LoadAllData() {
var reportTable = $('#AllSales').dataTable({
"processing": true,
//"bprocessing": true,
"bJQueryUI": false,
"bServerSide": true,
"bFilter": false,
//"bAutoWidth": true,
"bDestroy": true,
"iDisplayLength": 20,
//"sProcessing": "<img src=~/Content/images/ajax-loader.gif />",
"dom": 'T<"clear">lfrtip',
"sSwfPath": "~/swf/copy_csv_xls_pdf.swf",
"fnPreDrawCallback": function () {
$("#AllSales").hide();
$("#loading").show();
// alert("Pre Draw");
},
"fnDrawCallback": function () {
$("#AllSales").show();
$("#loading").hide();
// alert("Draw");
},
"fnInitComplete": function () {
},
"fnServerParams": function (aoData) {
aoData.push({ "name": "FromDate", "value": $("#FromDate").val() })
aoData.push({ "name": "ToDate", "value": $("#ToDate").val() })
},
"sAjaxSource": "/Report/AllSaleReport",
"footerCallback": function (row, aoData, start, end, display) {
var api = this.api(), aoData;
// Remove the formatting to get integer data for summation
var intVal = function (i) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '') * 1 :
typeof i === 'number' ?
i : 0;
};
// Total over all pages
data = api.column(4).data();
alert(data.length);
// alert(SalesReturn);
total = data.length ?
data.reduce(function (a, b) {
return intVal(a) + intVal(b);
}) :
0;
// Total over this page
data = api.column(4, { page: 'current' }).data();
pageTotal = data.length ?
data.reduce(function (a, b) {
return intVal(a) + intVal(b);
}) :
0;
// Update footer
$(api.column(4).footer()).html(
'$' + pageTotal + ' ( $' + total + ' total)'
);
}
});
};
I want to pass SaleTotal to DataTable or my View
How can I Pass SaleTotal from controller to view. I tried many ways but still my problem not solved.
If I understand this correctly the data you want is the data from the SaleTotal method.
That data is in the json returned from the AllSaleReport method:
return Json(new
{
...
SalesReturn = SaleTotal(FromDate, ToDate)
},
So when you call the AllSaleReport from DataTable use fnServerData to override the function that gets that data and insert it where you want it. Something like:
"fnServerData": function (sSource, aoData, fnCallback) {
$.getJSON(sSource, aoData, function (result) {
var saleTotal = result.SalesReturn;
// Insert saleTotal in footer
fnCallback(result);
});
},

OncellChange Event of Slickgrid

I have a slickgrid with a checkbox column.
I want to capture the row id when the checkbox in the selected row is checked or unchecked.
Attached is the script for slickgrid in my view
I want when user checks the checkbox, active column in database should be set to true and when it is unchecked, Active column should be set to false.
<script type="text/javascript">
//$('input[type="button"]').enabled(false);
var grid;
var columnFilters = {};
var jsonmodel = #Html.Raw(Json.Encode(Model));
//function LoadNewMessagesData(messages) {
var dataView;
var data = [];
////console.log('lena:' + subdata.length);
$.each(jsonmodel, function (idx, spotlight) {
var pd = moment(spotlight.PostedDate);
data.push({ id: spotlight.ID, Department: spotlight.SubSection,Title: spotlight.Title, PostedDate: pd.format('YYYY-MM-DD'), Active: spotlight.Active })
});
var columns = [
{ id: '0', name: "Department", field: "Department", sortable: true},
{ id: '1', name: "Title", field: "Title", sortable: true},
{ id: '2', name: "PostedDate", field: "PostedDate", sortable: true }
];
var checkboxSelector = new Slick.CheckboxSelectColumn({
cssClass: "slick-cell-checkboxsel"
})
columns.push(checkboxSelector.getColumnDefinition());
var options = {
enableCellNavigation: true,
explicitInitialization: true,
enableColumnReorder: false,
multiColumnSort: true,
autoHeight: true,
forceFitColumns: true
};
dataView = new Slick.Data.DataView();
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.setSelectionModel(new Slick.RowSelectionModel());
var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
grid.registerPlugin(checkboxSelector);
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
console.log('testing');
grid.render();
});
dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
var options = grid.getOptions();
if (options.enableAddRow != enableAddRow) {
grid.setOptions({ enableAddRow: enableAddRow });
}
});
var rowIndex;
grid.onCellChange.subscribe(function (e, args) {
console.log('onCellChange');
rowIndex = args.row;
});
if (grid.getActiveCell()) {
}
//onSelectedRowsChanged event, if row number was changed call some function.
grid.onSelectedRowsChanged.subscribe(function (e, args) {
if (grid.getSelectedRows([0])[0] !== rowIndex) {
console.log('onSelectedRowsChanged');
}
});
grid.onSort.subscribe(function (e, args) {
var cols = args.sortCols;
var comparer = function (dataRow1, dataRow2) {
for (var i = 0, l = cols.length; i < l; i++) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
return 0;
}
dataView.sort(comparer, args.sortAsc);
});
grid.init();
dataView.beginUpdate();
dataView.setItems(data);
// dataView.setFilter(filter);
dataView.endUpdate();
//}
function RefreshMessagesGrid() {
//console.log('RefreshMessagesGrid');
//grid.invalidate();
grid.invalidateRows();
// Call render to render them again
grid.render();
grid.resizeCanvas();
}
</script>`enter code here`
Thanks in Advance !!!
You have to bind click event on rows....and get the id of the row whose checkbox is checked/unchecked
function bindClickOnRow() {
if($(this).find('.checkboxClass').attr('checked') == 'checked'){
checked = true;
} else {
checked = false;
}
rowId = $(this).attr('id');
}

Resources