Reload data to textbox after jqgrid "reloadGrid" action - asp.net

I use a modal form to update/create my records "reloadGrid" method enables the grid enter image description here to refresh from within the modal "save" bouton, but
1) my form below does not get updated.
2) the last selected row on the jqGrid table gets not selected.
I tried to manualy force the row to be selected with
jQuery('#grid').jqGrid('setSelection', selRowID, true);
but selected row returns null.
Below is the function that saves the updated record and is suposed to trigger the grid and the controls update:
//function SauvegarderMessage(IDMessage) {
function ModifierDemandeur() {
//console.log("Modifier");
var xCodeDdeur = $('#txtCode_Demandeur').val();
var xAddDdeur = $('#txtAdresse_Demandeur').val();
var xIDVille = $('#cbxVille_Demandeur').val();
var xIDProv = $('#cbxProvince_Demandeur').val();
var xCPDdeur = $('#txtCodePostal_Demandeur').val();
var xTel1Ddeur = $('#txtTel1_Demandeur').val();
var xTel2Ddeur = $('#txtTel2_Demandeur').val();
var xTel3Ddeur = $('#txtTel3_Demandeur').val();
var xCour1Ddeur = $('#Courriel1_Demandeur').val();
var xCour2Ddeur = $('#Courriel2_Demandeur').val();
var xCour3Ddeur = $('#Courriel3_Demandeur').val();
var xIDSitMat = $('#cbxSitMat_Demandeur').val();
var xIDSexe = $('#cbxSexe_Demandeur').val();
var xDteNais = $('#txtDteNaissance').val();
var xRevDdeur = $('#txtrevenu_demandeur').val();
var xIDOcc = $('#cbxOccupation_Demandeur').val();
var xIDScol = $('#cbxScolarite_Demandeur').val();
var xIDStatLegal = $('#cbxStatutLegal_Demandeur').val();
var xIDComm = $('#cbxCommunaute_Demandeur').val();
var xIDSceInfo = $('#cbxSourceInformation_Demandeur').val();
var xHandicape = $('#cbHandi').val();
var xRef = $('#txtReference_Demandeur').val();
var xRemDdeur = $('#Remarques_Demandeur').val();
$.ajax({
type: "POST",
url: "../Conseiller/UpdateDemandeurs",
data: {
Code_Demandeur: xCodeDdeur,
Adresse_Demandeur: xAddDdeur,
ID_Ville: xIDVille,
ID_Province: xIDProv,
CodePostal_Demandeur: xCPDdeur,
Tel1_Demandeur: xTel1Ddeur,
Tel2_Demandeur: xTel2Ddeur,
Tel3_Demandeur: xTel3Ddeur,
Courriel1_Demandeur: xCour1Ddeur,
Courriel2_Demandeur: xCour2Ddeur,
Courriel3_Demandeur: xCour3Ddeur,
ID_SituationMatrimoniale: xIDSitMat,
ID_Sexe: xIDSexe,
Date_Naissance_Demandeur: xDteNais,
Revenu_Demandeur: xRevDdeur,
ID_Occupation: xIDOcc,
ID_Scolarite: xIDScol,
ID_StatutLegal: xIDStatLegal,
ID_Communaute: xIDComm,
ID_SourceInformation: xIDSceInfo,
Handicape: xHandicape,
Reference: xRef,
Remarques_Demandeur: xRemDdeur,
},
dataType: "json",
success: function (data) {
//console.log(data)
//console.log(data.rows);
$('#modifierProfilModal').modal('hide');
if (data != null) {
jQuery('#grid').jqGrid('clearGridData')
.jqGrid('setGridParam', { data: data, datatype: 'json' })
.trigger('reloadGrid')
for (var i = 0; i < data.Data.records; i += 1) {
var selRowID = data.Data.rows[i].Code_Demandeur;
var selectedRowID = $('#btnModifierProfile').val();
if (selRowID == selectedRowID) {
//jQuery('#grid').jqGrid('setSelection', selRowID, true);
var selr = jQuery('#grid').jqGrid('getGridParam', 'selrow');
console.log('Ligne sélectionnée: ' + selr);
return;
}
}
}
},
error: function (err) { console.log(err); }
});
I tried editRow action to force row selection, I tried to set focus to the grid, nothing would do.

A work around would be to identify each field with the last selected element's ID and assign each control appropriate value using document.getElementById('controlID').value = some_json_returned_data;
But this still not solve the grid row selection issue and does not seem to be a "best practice" way to do.

Coding the "loadComplete" method of qgrid resolved both issue:
loadComplete: function () {
if ($('#btnModifierProfile').val() != "")
jQuery('#grid').jqGrid('setSelection', $('#btnModifierProfile').val());
},
Desired row is selected and related data populated in other controls.

Related

FullCalendar RefetchEvents very slow

I call calendar.refetchEvents(); inside an autorun Block to ensure the reactivity of the Scheduler (i'm using resource view) , when tested with big datasets , although i make sure to subscript to only a portion of 2 weeks worth of events , it's extremly slow .
my events arent Json based i'm using meteor and i loop over the events inside the Events function of the calendar .
are there some good fullcalendar practices i'm missing ?
calendar = $('#calendar').fullCalendar({
now: new Date(),
editable: true, // enable draggable events
droppable: true, // this allows things to be dropped onto the calendar
aspectRatio: 1.8,
disableDragging: true,
displayEventTime: false,
selectable:true,
allDaySlot:true,
slotDuration:'24:00',
lazyFetching:true,
scrollTime: '00:00', // undo default 6am scrollTime
header: {
left: 'today prev,next',
center: 'title',
right: 'timelineThreeDays'
},
defaultView: 'timelineThreeDays',
views: {
timelineThreeDays: {
type: 'timeline',
duration: { days: 14 }
}
},
eventAfterAllRender: function(){
Session.set("loading",false);
},
resourceLabelText: 'Employees',
eventRender: function (event, element) {
var originalClass = element[0].className;
if (event.id && event.id.indexOf("temp")>-1){
element[0].className = originalClass + ' dragEvent';
}
else if (event.id && event.id.indexOf("oloc")>-1){
element[0].className = originalClass + ' oloc';
}
else{
element[0].className = originalClass + ' hasmenu';
}
$(element[0]).attr('shift-id', event._id);
element.find('.fc-title').html((event.title?event.title+"<br/>":"")+(event.locationName?event.locationName+"<br/>":"")+moment(event.start).format("HH:mm")+ " "+moment(event.end).format("HH:mm"));
element.bind('mousedown', function (e) {
if (e.which == 3) {
Session.set("selectedShift",event._id);
}
});
},eventAfterRender: function(event, element, view) {
},
resourceRender: function(resourceObj, labelTds, bodyTds) {
var originalClass = labelTds[0].className;
var uid=resourceObj.id;
var resource = Meteor.users.findOne({_id:uid});
if(resource){
var img = Images.findOne({_id: resource.picture});
var imgUrl = img ? img.url() : "/images/default-avatar.png";
var styleString = "<img class='img-profil small' src='"+imgUrl+"'>" + resource.profile.firstname + " " + resource.profile.lastname+" <small style='font-size:0.6em;color:#D24D57;'>"+resource.profile.registeredTelephony+"</small>";
labelTds.find('.fc-cell-text').html("");
labelTds.find('.fc-cell-text').prepend(styleString);
labelTds[0].className = originalClass + ' hasResourceMenu';
}else{
var imgUrl = "/images/default-avatar.png";
var styleString = "<img class='img-profil small' src='"+imgUrl+"'>" + "Unassigned" + " " +" <small style='font-size:0.6em;color:#D24D57;'>"+"</small>";
labelTds.find('.fc-cell-text').html("");
labelTds.find('.fc-cell-text').prepend(styleString);
}
},
resources: function(callback) {
var users = [];
var data = Meteor.users.find({
$or:[
{"profile.showInScheduler":{$exists:false}},
{"profile.showInScheduler":true}
],
assignedTo:{$in:[Session.get("locationId")]},
'locations._id':Session.get("locationId"),
"profile.companyId":Session.get("companyId")
});
var arr = data.map(function(c) {
var employeeType = c.userSettings.employeeType;
var type = EmployeeType.findOne({_id:employeeType});
var img = Images.findOne({_id: c.picture});
var imgUrl = img ? img.url() : "/images/default-avatar.png";
c.name = c.name || "";
var totalHoursAllLocation = 0;
var totalHoursCurrentLocation = 0;
return {
id: c._id,
title: "t"
};
});
arr.push({id:"temp"+Session.get("companyId")+Session.get("locationId"),title:"<div class='img-profil small' style='background: url(/images/default-avatar.png);'></div> UnAssigned"});
callback(arr);
},
events: function(start, end, timezone, callback) {
},
drop: function(date, jsEvent, ui, resourceId) {
// retrieve the dropped element's stored Event Object
var locationId=Session.get("locationId");
var originalEventObject = $(this).data('eventObject');
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
//copiedEventObject.allDay = allDay;
shift = ShiftTypes.findOne({_id:copiedEventObject.id});
if(shift){
startDate = moment(date);
hour = shift.dayDuration.Start.split(":");
startDate.hours(hour[0]).minutes(hour[1]);
endDate = moment(date);
hour = shift.dayDuration.End.split(":");
endDate.hours(hour[0]).minutes(hour[1]);
if(moment(startDate).isAfter(endDate)){
endDate=endDate.add("1","days");
}
var data = {
shiftId:shift._id,
name:shift.name,
uid:resourceId,
locationId:Session.get("locationId"),
companyId:Session.get("companyId"),
day:date,start:startDate.utc().toDate(),
end:endDate.utc().toDate(),
type:"active"
};
if (SchedulesBeforeInsert(data,"dropActive")){
Schedules.insert(data,function (err,result) {});
}
}
},
eventResize: function( event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ) {
endDate = moment.utc(new Date(event.start));
schedule = Schedules.findOne({_id:event.id});
var delta = dayDelta._days;
for(i=1;i<delta+1;i++){
Schedules.insert({start:moment.utc(event.start).add(i,"days").toDate(),end:moment.utc(schedule.end).add(i,"days").toDate(),uid:schedule.uid,locationId:Session.get("locationId"),companyId:schedule.companyId,name:schedule.name,shiftId:schedule.shiftId,attendanceCode:schedule.attendanceCode,type:schedule.type});
}
},
dayClick: function(date, jsEvent, view,res,res2) {
Session.set("selectedDay",moment(date).toDate());
Session.set("selectedRessource",res.id);
},
eventClick: function ( event, jsEvent, view ) {
toastr.success(moment(event.start).format('HH:mm') +" TO "+moment(event.endDate).format('HH:mm'))
},
eventReceive: function(event) { // called when a proper external event is dropped
console.log('eventReceive', event);
}
}).data().fullCalendar;
/********************* reactive calendar *****************/
this.autorun(function() {
console.log("autoRun")
Meteor.subscribe("schedules",Session.get("companyId"),moment($('#calendar').fullCalendar('getDate')).startOf('week').toDate(),moment($('#calendar').fullCalendar('getDate')).add(4,"weeks").endOf('week').toDate());
var events = [];
var usersInLocation = Meteor.users.find({$or:[{"profile.showInScheduler":{$exists:false}},{"profile.showInScheduler":true}],assignedTo:{$in:[Session.get("locationId")]},'locations._id':Session.get("locationId"),"profile.companyId":Session.get("companyId")}).fetch();
var userIds = _.pluck(usersInLocation,"_id");
userIds.push("temp"+Session.get("companyId")+Session.get("locationId"));
var data;
if(Session.get("displayAllLocations")===true){
reqEvents = Schedules.find({uid:{$in:userIds},companyId:Session.get("companyId"),type:{$in:["active","activeAttendance"]},start:{$gte:moment(Session.get("currentDate")).startOf('week').toDate()},end:{$lte:moment(Session.get("currentDate")).add(1,"week").endOf('week').toDate()}});
}else{
reqEvents = Schedules.find({uid:{$in:userIds},locationId:Session.get("locationId"),companyId:Session.get("companyId"),type:{$in:["active","activeAttendance"]},start:{$gte:moment(Session.get("currentDate")).startOf('week').toDate()},end:{$lte:moment(Session.get("currentDate")).add(1,"week").endOf('week').toDate()}});
}
reqEvents.forEach(function(evt){
var event = null;
color="";
if(evt.attendanceCode){
attendance =AttendanceCodes.findOne({_id:evt.attendanceCode});
color=attendance.color;
}
attendance = null;
color="";
id="";
locationName="";
if(evt.attendanceCode){
attendance =AttendanceCodes.findOne({_id:evt.attendanceCode})
if(attendance){
color=attendance.color;
}
}
else if(evt.employeeAttendanceCode){
attendance =AttendanceCodesPortal.findOne({_id:evt.employeeAttendanceCode})
if(attendance){
color=attendance.color;
}
}
id=evt._id;
if(evt.locationId!==Session.get("locationId")){
color="#EEEEEE";
id="oloc";
location =Locations.findOne({_id:evt.locationId});
if(location){
locationName=location.name;
}
}
if(evt.name != null){
event = {id:id,title:evt.name,start:evt.start,end:evt.end,color:color,resourceId:evt.uid,locationName:locationName};
}else{
event = {id:id,title:" ",start:evt.start,end:evt.end,color:color,resourceId:evt.uid,locationName:locationName};
}
events.push(event);
});
allUsersCursor =Meteor.users.find({
$or:[
{"profile.showInScheduler":{$exists:false}},
{"profile.showInScheduler":true}
],
assignedTo:{$in:[Session.get("locationId")]},
'locations._id':Session.get("locationId"),
"profile.companyId":Session.get("companyId")
}).fetch();
if(calendar){
calendar.removeEvents();
calendar.addEventSource(events);
calendar.refetchResources();
//SetUp the actions context menu
setUpContextMenu();
// Initialize the external events
$('#external-events div.external-event').each(function() {
var eventObject = {
title: $.trim($(this).text()), // use the element's text as the event title
id:$(this).attr("id")
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
helper: 'clone',
revert: 'invalid',
appendTo: 'body'// original position after the drag
});
});
}
});
I can see a number of non-Meteoric patterns in there that you should optimize out:
Your this.autorun will rerun anytime anything changes in your Schedules collection as well as for various user object changes (not just to the logged-in users but other users as well). Your autorun rebuilds your client-side data from scratch every time, including numerous joins. You could use a local collection to cache the joined data and then only add/change those documents when the underlying persisted document changes. This can be done with an observeChanges pattern. Or you could denormalize your data model a bit to avoid all those joins.
You're modifying the DOM by attaching events to a number of selectors using jQuery instead of using Meteor event handlers. This is also happening in your autorun which means you're attaching the same events to the same DOM objects repeatedly.
You use many Session variables and you use them repeatedly. These can be slow since they use browser local storage. You should .get() such data into a local variable once only and then refer to the local variable from then on.
Make sure that you only include fields in your Schedules publication that your code actually refers to on the client. The rest are overhead.

Reactive cursor without updating UI for added record

I am trying to make a newsfeed similar to twitter, where new records are not added to the UI (a button appears with new records count), but updates, change reactively the UI.
I have a collection called NewsItems and I a use a basic reactive cursor (NewsItems.find({})) for my feed. UI is a Blaze template with a each loop.
Subscription is done on a route level (iron router).
Any idea how to implement this kind of behavior using meteor reactivity ?
Thanks,
The trick is to have one more attribute on the NewsItem Collection Say show which is a boolean. NewsItem should have default value of show as false
The Each Loop Should display only Feeds with show == true and button should show the count of all the items with show == false
On Button click update all the elements in the Collection with show == false to show = true
this will make sure that all your feeds are shown .
As and when a new feed comes the Button count will also increase reactively .
Hope this Helps
The idea is to update the local collection (yourCollectionArticles._collection): all articles are {show: false} by default except the first data list (in order not to have a white page).
You detect first collection load using :
Meteor.subscribe("articles", {
onReady: function () {
articlesReady = true;
}
});
Then you observe new added data using
newsItems = NewsItems.find({})
newsItems.observeChanges({
addedBefore: (id, article, before)=> {
if (articlesReady) {
article.show = false;
NewsItems._collection.update({_id: id}, article);
}
else {
article.show = true;
NewsItems._collection.update({_id: id}, article);
}
}
});
Here is a working example: https://gist.github.com/mounibec/9bc90953eb9f3e04a2b3.
Finally I managed it using a session variable for the current date /time:
Template.newsFeed.onCreated(function () {
var tpl = this;
tpl.loaded = new ReactiveVar(0);
tpl.limit = new ReactiveVar(30);
Session.set('newsfeedTime', new Date());
tpl.autorun(function () {
var limit = tpl.limit.get();
var time = Session.get('newsfeedTime');
var subscription = tpl.subscribe('lazyload-newsfeed', time, limit);
var subscriptionCount = tpl.subscribe('news-count', time);
if (subscription.ready()) {
tpl.loaded.set(limit);
}
});
tpl.news = function() {
return NewsItems.find({creationTime: {$lt: Session.get('newsfeedTime')}},
{sort: {relevancy: -1 }},
{limit: tpl.loaded.get()});
},
tpl.countRecent = function() {
return Counts.get('recentCount');
},
tpl.displayCount = function() {
return Counts.get('displayCount');
}
});
Template.newsFeed.events({
'click .load-new': function (evt, tpl) {
evt.preventDefault();
var time = new Date();
var limit = tpl.limit.get();
var countNewsToAdd = tpl.countRecent();
limit += countNewsToAdd;
tpl.limit.set(limit);
Session.set('newsfeedTime', new Date());
}
});

MeteorJS: CALLBACKS

PROBLEM: I want to parse the elements in a page from another website, glue resulting elements in an object and insert it in a Mongo collection. Before insertion i want to check if my Mongo yet has an identical object. If it does it shall exit the running functions, otherwise i want the script to start parsing the next target.
Example:
I have a function that connects to a webpage and returns its body content
It is parsed
When <a></a> elements are met, another callback is called in which all parsed elements are merged in one object and inserted in a collection
My code :
var Cheerio = Meteor.npmRequire('cheerio');
var lastUrl;
var exit = false;
Meteor.methods({
parsing:function(){
this.unblock();
request("https://example.com/", Meteor.bindEnvironment(function(error, response, body) {
if (!error && response.statusCode == 200) {
$ = Cheerio.load(body);
var k = 1;
$("div.content").each(function() {
var name = $...//parsing
var age = $....//parsing
var url = $...//parsing <a></a> elements
var r = request("https://example.com/"+url, Meteor.bindEnvironment(function(error, response, body) {
lastUrl = response.request.uri.href;// get the last routing link
var metadata = {
name: name,
age: age
url: lastUrl
};
var postExist;
postExist = Posts.findOne(metadata); // return undefined if doesnt exist, AND every time postExist = undefined ??
if (!postExist){
Posts.insert(metadata);// if post doesnt exist (every time go here ??)
}
else {
exit = true; // if exist
}
}));
if (exit === true) return false;
});
}
}));
}
});
Problem 1 : The problem is my function works every time, but it doesn't stop even if the object exists in my collection
Problem 2 : postExist is always undefined
EDIT : The execution must stop and wait until the second request's response.
var url = $...//parsing <a></a> elements
//STOP HERE AND WAIT !!
var r = request("https://example.com/"+url, Meteor.bindEnvironment(function(error, response, body) {
Looks like you want the second request to be synchronous and not asynchronous.
To achieve this, use a future
var Cheerio = Meteor.npmRequire('cheerio');
var Future = Meteor.npmRequire('fibers/future');
var lastUrl;
var exit = false;
Meteor.methods({
parsing:function(){
this.unblock();
request("https://example.com/", Meteor.bindEnvironment(function(error, response, body) {
if (!error && response.statusCode == 200) {
$ = Cheerio.load(body);
var k = 1;
$("div.content").each(function() {
var name = $...//parsing
var age = $....//parsing
var url = $...//parsing <a></a> elements
var fut = new Future();
var r = request("https://example.com/"+url, Meteor.bindEnvironment(function(error, response, body) {
lastUrl = response.request.uri.href;// get the last routing link
var metadata = {
name: name,
age: age
url: lastUrl
};
var postExist;
postExist = Posts.findOne(metadata); // return undefined if doesnt exist
if (!postExist) {
Posts.insert(metadata);// if post doesnt exist (every time go here ??)
fut.return(true);
} else {
fut.return(false);
}
}));
var status = fut.wait();
return status;
});
}
}));
}
});
You can use futures whenever you can't utilize callback functions (e.g. you want the user to wait on the result of a callback before presenting info).
Hopefully that helps,
Elliott
This is the opposite :
postExist = Posts.findOne(metadata); // return undefined if doesnt exist > you're right
if (!postExist){ //=if NOT undefined = if it EXISTS !
Posts.insert(metadata);
}else {
exit = true; // if undefined > if it DOES NOT EXIST !
}
You need to inverse the condition or the code inside

This is my code when I insert multi record into my Collection first time it work but when i insert second time it say duplicate _id,

This is my code when I insert multi record into my Collection first time it work well but when i insert second time it say duplicate _id, how to fix it.
//Save Journal Detail
$("#item-list tr").each(function (e) {
//debugger;
var yearMonth = $('#journalDate').val();
var date = moment(yearMonth).format("YYMM");
var prefix = curBranch + "-" + date;
var chartAccountId = $(this).find(".chart-account-id option:selected").val();
if (chartAccountId == "" || chartAccountId == null) {
return;
}
var journalDetailId = idGenerator.genWithPrefix(Acc.Collection.JournalDetail, prefix, 8);
var debit = parseFloat($(this).find(".debit").val());
var credit = parseFloat($(this).find(".credit").val());
if (debit > 0) {
Acc.Collection.JournalDetail.insert({
_id: journalDetailId,
journalId: doc._id,
chartAccountId: chartAccountId,
drCr: debit,
split: "Hello"
});
} else {
Acc.Collection.JournalDetail.insert({
_id: journalDetailId,
journalId: doc._id,
chartAccountId: chartAccountId,
drCr: -credit,
split: "Hello"
});
}
});
return doc;
The problem is likely to be that your $.each() iterations do not wait for your insert calls to finish, therefore the last id in the collection stays the same, and therefore idGenerator.genWithPrefix gives you the same id for multiple successive insert calls.
In the Meteor client, "insert never blocks". So you would have to wait on each insert call before getting the next id via idGenerator.genWithPrefix, or else your next generated id will end up being the same as the previous one you started to insert.
One easy solution could be to transfer that logic to the server (where insert calls are blocking) using a method call, by only giving it the list of documents you wish for it to insert.
On the client:
//Save Journal Detail
var listToInsert = [];
var yearMonth = $('#journalDate').val();
var date = moment(yearMonth).format("YYMM");
var prefix = curBranch + "-" + date;
$("#item-list tr").each(function (e) {
//debugger;
var chartAccountId = $(this).find(".chart-account-id option:selected").val();
if (chartAccountId == "" || chartAccountId == null) {
return;
}
var debit = parseFloat($(this).find(".debit").val());
var credit = parseFloat($(this).find(".credit").val());
listToInsert.push({
journalId: doc._id,
chartAccountId: chartAccountId,
drCr: debit > 0 ? debit : -credit, // simplified with a ternary operator
split: "Hello"
});
});
Meteor.call("insertEntries", listToInsert, prefix, function () {
//done!
});
return doc;
On the server:
Meteor.methods({
'insertEntries': function (listToInsert, prefix) {
for (var i = 0; i < listToInsert.length; i++) {
listToInsert[i]._id = idGenerator.genWithPrefix(Acc.Collection.JournalDetail, prefix, 8);
// Since we're on the server, this insert will be blocking
Acc.Collection.JournalDetail.insert(listToInsert[i]);
}
}
});

Kendo UI adding row at Runtime(Client Side)

I am able to add a row at runtime using .js file into Kendo Data Source, but I havent seen from the form(UI), I followed the below steps
var vgrid = $("#grdEntitys").data("kendoGrid");
var datasource = vgrid.dataSource;
var newRecord = { No: "8164",ModellNo: "147",ID: "Test01", Name: "TEST"}
datasource.insert(newRecord);
then It throws an error "TypeError: Cannot read property 'AttributeValue' of undefined",
if we look at the console log, I am able to see the incrmented rows count as well as the newly inserted record. But in UI there is no change(UI Grid).
could you please anyone let me know, how to add row at client side?
Thanks in advance
For insert you have to specify index (Insert) :
var dataItem = dataSource.insert(0, { name: "John Doe" });
Alternatively you could use Add where you don't have to specify the index:
<script>
var dataSource= new kendo.data.DataSource({
data: [
{ name: "Jane Doe", age: 30 }
]
});
dataSource.add({ name: "John Doe", age: 33 });
you can use the script in you event to add item in your grid.
var dataSource = $("#CustomerPackageChannelKendoGridAdd").data("kendoGrid").dataSource;
// Get value from another field
var _JV_ACCOUNT_ID = $('#JV_ACCOUNT_ID').val();
var _JV_ACCOUNT_NAME = $('#JV_ACCOUNT_NAME').val();
var _JV_ACCOUNT_CODE = $('#JV_ACCOUNT_CODE').val();
var _JV_NOTES = $('#JV_NOTES').val();
var _JV_DATE = $('#JV_DATE').val();
var type = $('#JV_Transaction_TYPE').val();
// You can set condition if required for you
if (CheckExistingData(gridDataAdd, _JV_ACCOUNT_ID) == false) {
currentId += 1;
dataSource.add(
{
id: currentId,
JV_ACCOUNT_ID: _JV_ACCOUNT_ID,
JV_ACCOUNT_NAME: _JV_ACCOUNT_NAME
, JV_ACCOUNT_CODE: _JV_ACCOUNT_CODE
, JV_NOTES: _JV_NOTES
, JV_DATE: _JV_DATE
, JV_DEBIT_AMOUNT: _JV_DEBIT_AMOUNT
, JV_CREDIT_AMOUNT: _JV_CREDIT_AMOUNT
});
}
For more you can also see this:

Resources