Tabulator - Set data - javascript

I'm using a multi step form, "https://www.jqueryscript.net/demo/Signup-Form-Wizard-jQuery-multiStepForm/"this is the link that ı use. while multi step form page is opening, I call the load function and I also call data in my database with ajax. When I called the data I created a tableData object and I set this object to the tabuator table that I have specified.
Jquery Version:3.4.1;
Tabulator Version:4.5;
HTML
<script src="~/Content/js/jquery-3.4.1.min.js"></script>
<script src="~/Content/js/jquery-ui.min.js"></script>
<script src="~/Content/js/tabulator.min.js"></script>
<script src="~/Content/js/jquery_wrapper.min.js"></script>
JavaScript
var table;
// Define Date Editor
var dateEditor = function (cell, onRendered, success, cancel, editorParams) {
var cellValue = cell.getValue(),
var input = document.createElement("input");
input.setAttribute("type", "text");
input.style.padding = "4px";
input.style.width = "100%";
input.style.boxSizing = "border-box";
input.value = typeof cellValue !== "undefined" ? cellValue : "";
onRendered(function () {
$(input).datepicker({
dateFormat: "dd-mm-yy",
altFormat: "dd-mm-yy",
changeMonth: true,
changeYear: true,
yearRange: '-119:+119',
monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayis", "Haziran", "Temmuz", "A?ustos", "Eylul", "Ekim", "Kasım", "Aralık"],
monthNamesShort: ["Ock", "Şub", "Mart", "Nis", "May", "Haz", "Tem", "Agst", "Eyl", "Ekm", "Kas", "Ar"],
dayNamesMin: ["Pa", "Pt", "Sl", "Ca", "Pe", "Cu", "Ct"],
firstDay: 1,
onSelect: function (dateStr) {
var dateselected = $(this).datepicker('getDate');
var cleandate = (moment(dateselected, "DD-MM-YYYY").format("DD-MM-YYYY"));
$(input).datepicker("destroy");
cell.setValue(cleandate, true);
cancel();
},
});
input.style.height = "100%";
});
return input;
};
//Create Table
var table = new Tabulator("#example-table", {
columns: [
{ title: "Davalı Türü", field: "davalitur", editor: "select", editorParams: { values: { "Seçiniz": "Seçiniz", "Kişi": "Kişi", "Kurum": "Kurum" } } },
{ title: "Davalı", field: "adsoyadkurum", editor: "input" },
{ title: "Kusur Oranı", field: "kusuroran", editor: "input" },
{ title: "Sigorta Şirket Ünvanı", field: "unvan", editor: "input" },
{ title: "İhbar Tarihi", field: "sit", align: "center", sorter: "date", editor: dateEditor },
{ title: "Temerrüte Düşme Tarihi", field: "tdt", align: "center", sorter: "date", editor: dateEditor },
{ title: "Faiz Oranı", field: "faizorani", editor: "select", editorParams: { values: { "Kanuni Faiz Oranı": "Kanuni Faiz Oranı", "Ticari Faiz Oranı": "Ticari Faiz Oranı" } } },
{ title: "Ödemeyi Yapan", field: "odemeyapanselectval", editor: "select", editorParams: { values: { "Seçiniz": "Seçiniz", "Davalı": "Davalı", "Sigortacı": "Sigortacı" } } },
{ title: "Ödeme Yapılan", field: "odemeyapilandavaci", editor: "select", editorParams: { values: { "Eşi": "Eşi", "Çocuk": "Çocuk", "Anne-Baba": "Anne-Baba", "Diğer": "Diğer" } } },
{ title: "Ödeme Tarihi", field: "odemetarih", align: "center", sorter: "date", editor: dateEditor },
{ title: "Ödeme Tutarı", field: "odemetutar", editor: "input" },
{ title: "Güvence Ödeme Tarihi", field: "guvenceodemetarih", align: "center", sorter: "date", editor: dateEditor },
{ title: "Güvence Ödeme Tutarı", field: "guvenceodemetutar", editor: "input" },
{title: "Durum", formatter: "buttonCross", align: "center", cellClick: function (e, cell) {
cell.getRow().delete();
//if (confirm('İlgili davalı silinecekt')) cell.getRow().delete();//Dialog Eklenicek
}
},
],
});
// Step 4 load function
function dykstep4Yukle() {
$.ajax({
type: 'POST',
dataType: 'json',
cache: 'false',
url: '../Client2DB/DykStepGetir',
data: { projeid: projeId, stepNo: 4 },
success: function (data) {
counterloaddyk++;
if (counterloaddyk == 5) {
$('#pre-load').fadeOut();
}
var obj = JSON.parse(data.json);
$('#pre-load').fadeOut();
$.each(obj.DavaliTabloListe, function (key, value) {
tableData = [{
id: value.id,
davalitur: value.davalitur,
adsoyadkurum: value.AdSoyadKurum,
kusuroran: value.KusurOranı,
unvan: value.SigortaSirketUnvan,
sit: value.SigortaIhbarTarih,
tdt: value.TemerruteDusmeTarihi,
faizorani: value.faizorani ,
odemeyapanselectval: value.OdemeyiYapanKurum,
odemeyapilandavaci: value.davaciturstring,
odemetarih: value.loadOdemeTarihi,
odemetutar: value.loadOdemeTutari ,
guvenceodemetarih: value.loadGuvenceOdemeTarihi,
guvenceodemetutar: value.loadGuvenceOdemeTutar
}];
});
createTable(tableData);
}, error: function () {
alert("DYKT step 4 error");
}
});
}
//Set Data
function createTable(tableData) {
if (tableData.length>0) {
table.setData(tableData);
}
}
When I call table.setData(tableData) , data is on success but table shows empty. when I click on any title of the table, data displays.(so it is the trigger) but normally table comes out as empty.
enter image description here
enter image description here 2

This is happening because the table was not visible when the data was loaded into the table.
You need to call the redraw function on the table when you make it visible.
table.redraw();

Related

Kendo UI Grid Item Create Function Not Being Called

I made a kendo grid with a toolbar to create new records, but when the update button is pressed the create function in the data source I expect to be called isn't being called. I took this code from another page in the code where it works perfectly fine and I scanned both page to make sure I'm not missing any sort of library and on top of that the debugger isn't outputting anthing either.
var RegionalMappingDataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax({
url: siteRoot + '/Admin/RegionMapping/GetRegionMappings',
type: 'GET',
success: function(result) {
options.success(result);
},
error: function(result) {
options.error(result);
}
});
},
create: function () { // This is the method I expected to be called
console.log("it hits create");
},
save: function () { // Checked to make sure this method isn't called
console.log("it hits save");
}
}
});
$("#Regionmappinggrid").kendoGrid({
dataSource: RegionalMappingDataSource,
groupable: false,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
editable: "inline",
toolbar: [{ name: "create", text: "Update Other Region Name" }], // where I tried to bind to method
columns: [
{
title: "Country Name",
field: "CountryCode",
editor: function(container, options) {
var input = $('<input required id="mapping" name="' + options.field + '"/>');
input.appendTo(container);
input.kendoDropDownList({
autoBind: true,
optionLabel: 'Please Select Country....',
dataTextField: "Value",
dataValueField: "Key",
dataSource: getCountryName,
value: options.model.Key,
text: options.model.Value
}).appendTo(container);
}
},
{
title: "Region Name",
field: "RegionName",
editor: function(container, options) {
var input = $('<input required id="mapping1" name="' + options.field + '"/>');
input.appendTo(container);
input.kendoDropDownList({
autoBind: false,
optionLabel: 'Please Select Region....',
dataTextField: "Value",
dataValueField: "Key",
dataSource: getRegionName,
value: options.model.Key,
text: options.model.Value
}).appendTo(container);
}
},
{
title: "Region ID",
field: "RegionId",
hidden: true
},
{
title: "Other Name",
field: "Name"
},
{
title: "Updated On",
field: "UpdatedDate",
format: "{0: yyyy-MM-dd HH:mm:ss}",
editable: function() { return false; }
},
{
command: ["edit", "destroy"]
}
]
});
The Create function of the DataSource is called when the user presses the "Update" button that is rendered on the row of the new item. Can you confirm that upon pressing the "Update" button, the function is executed as expected?
As per automatically calling the Create function after the "Add new item" button is clicked, you should set the AutoSync property of the DataSource to "true". This would cause it to update automatically right after every change.
[https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/autosync][AutoSync property]


Kendo UI Grid : Drag and Drop Hierarchy not working

I want to drag and drop in different Grid with hierarchical data.
The Drag and drop is working fine but the row is not dropping in Detail item in destination grid.
I have created the sample here. here is the sample for the same..
The following code shows how i built this, but getting some issues in the same. Please help me out what mistake i am doing in this?
function convert(array) {
var map = {};
for (var i = 0; i < array.length; i++) {
var obj = array[i];
obj.items = [];
map[obj.DemographicId] = obj;
var parent = obj.ParentId || '-';
if (!map[parent]) {
map[parent] = {
items: []
};
}
map[parent].items.push(obj);
}
return map['-'].items;
}
var arr = [{"Level":1,"DemographicId":13,"ParentId":null,"Name":"Bewitched General","Description":0.335336528},{"Level":2,"DemographicId":349,"ParentId":13,"Name":"Unacceptable Experience","Description":0.335336528},{"Level":1,"DemographicId":14,"ParentId":null,"Name":"Trained Trust","Description":29.17427794},{"Level":2,"DemographicId":329,"ParentId":14,"Name":"Concerned Rest","Description":0.335336528},{"Level":2,"DemographicId":331,"ParentId":14,"Name":"Tough Sleep","Description":2.012019168},{"Level":3,"DemographicId":346,"ParentId":331,"Name":"Icy Coffee","Description":0.335336528},{"Level":3,"DemographicId":347,"ParentId":331,"Name":"Big Fix","Description":0.335336528},{"Level":3,"DemographicId":348,"ParentId":331,"Name":"Total Worry","Description":0.335336528},{"Level":3,"DemographicId":431,"ParentId":331,"Name":"Fast Discipline","Description":0.335336528},{"Level":3,"DemographicId":586,"ParentId":331,"Name":"Intrepid Sister","Description":0.335336528},{"Level":2,"DemographicId":376,"ParentId":14,"Name":"Hasty Ordinary","Description":0.335336528},{"Level":2,"DemographicId":428,"ParentId":14,"Name":"Unnatural Native","Description":1.006009584},{"Level":3,"DemographicId":442,"ParentId":428,"Name":"Tan Celebration","Description":0.335336528},{"Level":3,"DemographicId":492,"ParentId":428,"Name":"Wise Repair","Description":0.335336528},{"Level":2,"DemographicId":443,"ParentId":14,"Name":"Frightening Historian","Description":3.018028753},{"Level":3,"DemographicId":328,"ParentId":443,"Name":"Improbable Stage","Description":0.335336528},{"Level":3,"DemographicId":517,"ParentId":443,"Name":"Heavenly Debt","Description":0.335336528},{"Level":3,"DemographicId":526,"ParentId":443,"Name":"That Art","Description":2.012019168},{"Level":4,"DemographicId":524,"ParentId":526,"Name":"Vivacious Competition","Description":0.670673056},{"Level":5,"DemographicId":445,"ParentId":524,"Name":"Dependable Potato","Description":0.335336528},{"Level":4,"DemographicId":525,"ParentId":526,"Name":"Watchful Tough","Description":1.006009584},{"Level":5,"DemographicId":432,"ParentId":525,"Name":"Lovable Sing","Description":0.670673056},{"Level":6,"DemographicId":435,"ParentId":432,"Name":"Vengeful Cigarette","Description":0.335336528},{"Level":2,"DemographicId":522,"ParentId":14,"Name":"Insistent Offer","Description":0.335336528},{"Level":2,"DemographicId":590,"ParentId":14,"Name":"Oddball Airline","Description":0.335336528},{"Level":2,"DemographicId":591,"ParentId":14,"Name":"Back Outcome","Description":20.79086474},{"Level":3,"DemographicId":330,"ParentId":591,"Name":"Mushy Active","Description":0.335336528},{"Level":3,"DemographicId":427,"ParentId":591,"Name":"Immaterial Safety","Description":1.341346112},{"Level":4,"DemographicId":437,"ParentId":427,"Name":"Same Restaurant","Description":0.335336528},{"Level":4,"DemographicId":438,"ParentId":427,"Name":"Imaginary Brother","Description":0.335336528},{"Level":4,"DemographicId":613,"ParentId":427,"Name":"Bubbly Hole","Description":0.335336528},{"Level":3,"DemographicId":433,"ParentId":591,"Name":"Several Weird","Description":2.682692225},{"Level":4,"DemographicId":426,"ParentId":433,"Name":"Deadly Potato","Description":0.335336528},{"Level":4,"DemographicId":436,"ParentId":433,"Name":"Ornery Race","Description":0.335336528},{"Level":4,"DemographicId":440,"ParentId":433,"Name":"Trusting Native","Description":0.335336528},{"Level":4,"DemographicId":441,"ParentId":433,"Name":"Flowery Tower","Description":0.335336528},{"Level":4,"DemographicId":479,"ParentId":433,"Name":"Downright Fall","Description":0.335336528},{"Level":4,"DemographicId":480,"ParentId":433,"Name":"Unique Career","Description":0.335336528},{"Level":4,"DemographicId":614,"ParentId":433,"Name":"Unknown Thomas","Description":0.335336528},{"Level":3,"DemographicId":592,"ParentId":591,"Name":"Judicious Analyst","Description":0.335336528},{"Level":3,"DemographicId":593,"ParentId":591,"Name":"Hard Major","Description":0.335336528},{"Level":3,"DemographicId":595,"ParentId":591,"Name":"Naughty Temporary","Description":0.335336528},{"Level":3,"DemographicId":596,"ParentId":591,"Name":"Crisp Commission","Description":0.335336528},{"Level":3,"DemographicId":597,"ParentId":591,"Name":"Valid Funny","Description":0.335336528},{"Level":3,"DemographicId":598,"ParentId":591,"Name":"Luminous Log","Description":0.335336528},{"Level":3,"DemographicId":599,"ParentId":591,"Name":"Sour Introduction","Description":0.335336528},{"Level":3,"DemographicId":600,"ParentId":591,"Name":"Elegant Player","Description":0.335336528},{"Level":3,"DemographicId":601,"ParentId":591,"Name":"Wilted Scheme","Description":1.006009584},{"Level":4,"DemographicId":444,"ParentId":601,"Name":"That Research","Description":0.335336528},{"Level":4,"DemographicId":609,"ParentId":601,"Name":"Overcooked Message","Description":0.335336528},{"Level":3,"DemographicId":602,"ParentId":591,"Name":"Good-natured Responsibility","Description":3.688701809},{"Level":4,"DemographicId":478,"ParentId":602,"Name":"Cumbersome Battle","Description":0.335336528},{"Level":4,"DemographicId":515,"ParentId":602,"Name":"Unsightly Contest","Description":2.682692225},{"Level":5,"DemographicId":439,"ParentId":515,"Name":"Mushy Explanation","Description":0.335336528},{"Level":5,"DemographicId":508,"ParentId":515,"Name":"Obvious Pride","Description":0.670673056},{"Level":6,"DemographicId":509,"ParentId":508,"Name":"Negligible Ask","Description":0.335336528},{"Level":5,"DemographicId":514,"ParentId":515,"Name":"Concerned Classic","Description":1.341346112},{"Level":6,"DemographicId":510,"ParentId":514,"Name":"Greedy Double","Description":0.335336528},{"Level":6,"DemographicId":511,"ParentId":514,"Name":"Reflecting Poem","Description":0.335336528},{"Level":6,"DemographicId":512,"ParentId":514,"Name":"Every Finish","Description":0.335336528},{"Level":4,"DemographicId":610,"ParentId":602,"Name":"Zigzag Meet","Description":0.335336528},{"Level":3,"DemographicId":603,"ParentId":591,"Name":"Esteemed Satisfaction","Description":0.335336528},{"Level":3,"DemographicId":604,"ParentId":591,"Name":"Normal Trouble","Description":1.341346112},{"Level":4,"DemographicId":485,"ParentId":604,"Name":"Hot Fish","Description":0.335336528},{"Level":4,"DemographicId":611,"ParentId":604,"Name":"Eager Perception","Description":0.335336528},{"Level":4,"DemographicId":612,"ParentId":604,"Name":"Shocking Aside","Description":0.335336528},{"Level":3,"DemographicId":605,"ParentId":591,"Name":"Terrific King","Description":0.335336528},{"Level":3,"DemographicId":606,"ParentId":591,"Name":"Humiliating Suit","Description":0.335336528},{"Level":3,"DemographicId":607,"ParentId":591,"Name":"Serious Smile","Description":0.335336528},{"Level":3,"DemographicId":608,"ParentId":591,"Name":"Memorable Ship","Description":3.353365281},{"Level":4,"DemographicId":430,"ParentId":608,"Name":"Wan Science","Description":0.335336528},{"Level":4,"DemographicId":434,"ParentId":608,"Name":"Hard Rule","Description":0.335336528},{"Level":4,"DemographicId":473,"ParentId":608,"Name":"Marvelous Radio","Description":0.335336528},{"Level":4,"DemographicId":477,"ParentId":608,"Name":"Visible Personality","Description":0.335336528},{"Level":4,"DemographicId":481,"ParentId":608,"Name":"Scrawny Shine","Description":0.335336528},{"Level":4,"DemographicId":507,"ParentId":608,"Name":"Descriptive Pride","Description":0.335336528},{"Level":4,"DemographicId":516,"ParentId":608,"Name":"Pleased Private","Description":0.335336528},{"Level":4,"DemographicId":548,"ParentId":608,"Name":"Frizzy District","Description":0.335336528},{"Level":4,"DemographicId":615,"ParentId":608,"Name":"Juicy Organization","Description":0.335336528},{"Level":3,"DemographicId":616,"ParentId":591,"Name":"Sweaty Equal","Description":0.335336528},{"Level":3,"DemographicId":621,"ParentId":591,"Name":"Sweltering Cigarette","Description":0.335336528},{"Level":3,"DemographicId":623,"ParentId":591,"Name":"Buoyant Rule","Description":0.335336528},{"Level":3,"DemographicId":625,"ParentId":591,"Name":"Whimsical Remote","Description":0.335336528},{"Level":3,"DemographicId":633,"ParentId":591,"Name":"Notable Feed","Description":0.335336528},{"Level":3,"DemographicId":635,"ParentId":591,"Name":"Puzzled Pin","Description":1.006009584},{"Level":4,"DemographicId":594,"ParentId":635,"Name":"Plump Member","Description":0.335336528},{"Level":4,"DemographicId":636,"ParentId":635,"Name":"Colorless Service","Description":0.335336528},{"Level":2,"DemographicId":618,"ParentId":14,"Name":"Extroverted Excuse","Description":0.335336528},{"Level":2,"DemographicId":622,"ParentId":14,"Name":"Definite Sector","Description":0.335336528},{"Level":2,"DemographicId":631,"ParentId":14,"Name":"Dear Blue","Description":0.335336528},{"Level":1,"DemographicId":15,"ParentId":null,"Name":"Weird Rush","Description":3.688701809},{"Level":2,"DemographicId":461,"ParentId":15,"Name":"Vigilant Mine","Description":0.335336528},{"Level":2,"DemographicId":527,"ParentId":15,"Name":"Darling Cousin","Description":2.682692225},{"Level":3,"DemographicId":504,"ParentId":527,"Name":"Courteous Knife","Description":0.335336528},{"Level":3,"DemographicId":528,"ParentId":527,"Name":"Constant Window","Description":2.012019168},{"Level":4,"DemographicId":6,"ParentId":528,"Name":"Serene Personal","Description":0.335336528},{"Level":4,"DemographicId":518,"ParentId":528,"Name":"Cooperative Marketing","Description":0.335336528},{"Level":4,"DemographicId":530,"ParentId":528,"Name":"Likely Car","Description":0.335336528},{"Level":4,"DemographicId":531,"ParentId":528,"Name":"Worst Lip","Description":0.335336528},{"Level":4,"DemographicId":550,"ParentId":528,"Name":"Quintessential Evening","Description":0.335336528},{"Level":2,"DemographicId":529,"ParentId":15,"Name":"Knowing Debt","Description":0.335336528},{"Level":2,"DemographicId":587,"ParentId":15,"Name":"Harmless Weight","Description":0.335336528},{"Level":1,"DemographicId":16,"ParentId":null,"Name":"Tidy Mouse","Description":2.012019168},{"Level":2,"DemographicId":5,"ParentId":16,"Name":"Useless Chemistry","Description":0.335336528},{"Level":2,"DemographicId":254,"ParentId":16,"Name":"Several Expert","Description":0.335336528},{"Level":2,"DemographicId":486,"ParentId":16,"Name":"Young String","Description":0.335336528},{"Level":2,"DemographicId":519,"ParentId":16,"Name":"Ideal Army","Description":1.006009584},{"Level":3,"DemographicId":520,"ParentId":519,"Name":"Tart Text","Description":0.335336528},{"Level":3,"DemographicId":521,"ParentId":519,"Name":"Tiny Church","Description":0.335336528}]
var myData = convert(arr)
var dataSource1 = new kendo.data.DataSource({
data: myData
});
$(document).ready(function () {
var originalGrid = $("#originalGrid").kendoGrid({
dataSource: dataSource1,
sortable: false,
pageable: false,
detailInit: detailInit1,
dataBound: function () {
//this.expandRow(this.tbody.find("tr.k-master-row").last());
},
columns: [
{
field: "Name",
title: "Name",
width: "80px"
},
{
field: "Description",
title: "Amount",
width: "30px",
aggregates: ["sum"],
groupFooterTemplate: "Sum: #= sum # "
}
]
});
});
function detailInit1(e) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: {
data: e.data.items //data is the current position item, items is its child items
},
scrollable: false,
sortable: false,
pageable: false,
detailInit: detailInit1,
columns: [
{
field: "Name",
title: "Name",
width: "80px"
},
{
field: "Description",
title: "Amount",
width: "30px",
aggregates: ["sum"],
groupFooterTemplate: "Sum: #= sum # "
}
]
});
}
$(document).ready(function () {
var dataSource2 = new kendo.data.DataSource({
data: []
});
var grid2 = $("#grid2").kendoGrid({
dataSource: dataSource2,
width: 400,
sortable: false,
pageable: false,
detailInit: detailInit11,
schema: {
model: {
id: "DemographicId"
}
},
columns: [
{
field: "Name",
title: "Name",
width: "40px"
},
{
field: "Description",
title: "Amount",
width: "110px",
aggregates: ["sum"],
groupFooterTemplate: "Sum: #= sum # "
}
]
});
function detailInit11(e) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: {
data: e.data.items
},
scrollable: false,
sortable: false,
pageable: false,
detailInit: detailInit11,
columns: [
{
field: "Name",
title: "Name",
width: "110px"
},
{
field: "Description",
title: "Amount",
width: "110px",
aggregates: ["sum"],
groupFooterTemplate: "Sum: #= sum # "
}
]
});
}
$(originalGrid).kendoDraggable({
filter: "tr",
hint: function (e) {
var item = $('<div class="k-grid k-widget" style="background-color: DarkOrange; color: black;"><table><tbody><tr>' + e.html() + '</tr></tbody></table></div>');
return item;
},
group: "gridGroup1",
});
var currentDataItem = null;
function getItemByUid(uid, currentUid, data) {
for (let index = 0; index < data.length; index++) {
const element = data[index];
if (element.uid == currentUid) {
currentDataItem = element;
return false;
} else {
if (element.items) {
getItemByUid(element.uid, currentUid, element.items);
}
}
}
}
grid2.kendoDropTarget({
drop: function (e) {
var uid = e.draggable.currentTarget.data("uid");
var dataItem = getItemByUid(uid, uid, dataSource1.data());
dataSource2.add(currentDataItem);
},
group: "gridGroup1",
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.mobile.all.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/kendo.all.min.js"></script>
</head>
<body>
<div>
<div style="width:50%;float:left" class="dragGrid">
<div id="originalGrid"></div>
</div>
<div style="width:50%;float:right" >
<div id="grid2"></div>
</div>
</div>
</body>
</html>
You need to handle the drop target for the detail grids as well. Use the - almost - same code for kendoDropTarget to your detail grid:
gridDetail.kendoDropTarget({
drop: function (e) {
var uid = e.draggable.currentTarget.data("uid");
var dataItem = getItemByUid(uid, uid, dataSource1.data());
$(e.dropTarget).data("kendoGrid").dataSource.add(currentDataItem);
},
group: "gridGroup1",
});
Demo

jqGrid FilterToolbar with mostly working daterange picker

I am using the free jqGrid v4.12.1. (Can't post links to fiddle yet so code follows post)
The primary issue is that we are trying to do all searching/filtering with the filterToolbar. Oleg had helped a few weeks back push just dates to the search modal, but the requirement has changed to get a date range picker working in the filterToolbar. We are mostly there. Using Dan Grossman's bootstrap daterange picker and calling a custom function, it works like a charm.
Entering DateRangeFirst
The problem originally came in to play when you would select another value like an invoice amount. It would then override the date range and give all values "ge" to the start date. So it was seeing the beginning date of the string. To circumvent this, I called the invoiceDateSearch function again in beforeSearch. This way it ran the function again and recognized the start date and end dates along with the new value we are asking for.
The thing that happens now is that if I put any other value in first and then select a daterange, the daterange won't fire until I key some other search criteria and back it out.
AnyOther value first
It doesn't even recognize the date range was entered yet, when clearly it is there. triggerToolbar, reload grid is called in the function for the invoice date search.
When using beforeSearch, keeps the date range as a date range and not a string...regardless of how often the toolbar is triggered and values are backed out of any other fields, which is great. The downside to it is if a user puts a value other than the date range FIRST, the date range doesn't work...unless a subsequent field is entered. Not using it, converts the date range to a string after the first time it is used and any other values entered or filtered will require re-running the date parameters, because it gives every date greater than the start date.
I've put advanced search on the grid while troubleshooting. I'd like to take it off (or at least the buttons), as users want to just use the toolbarFilter.
My questions, how can I get the date range picker working in concert with the other column values? Is there an issue running two date pickers at once? The single date date picker just isn't responding at all when it's used. It will put the date there, and once another field is fired, it will respond, but never by itself.
Sorry if I "info dumped" I am fairly new at this. I've searched quite a bit for help to this and can't find much of anything. If I keep hacking at this, I am going to tear up what I have working! :O
Thanks in advance for any help or guidance!
$(function () {
"use strict";
var $grid = $("#vGrid2"),
lastSel;
function modifySearchingFilter(separator) {
var i,
l,
rules,
rule,
parts,
j,
group,
str,
filters = $.parseJSON(this.p.postData.filters);
if (filters && typeof filters.rules !== 'undefined' && filters.rules.length > 0) {
rules = filters.rules;
for (i = 0; i < rules.length; i++) {
rule = rules[i];
if (rule.op === 'cn') {
// make modifications only for the 'contains' operation
parts = rule.data.split(separator);
if (parts.length > 1) {
if (typeof filters.groups === 'undefined') {
filters.groups = [];
}
group = {
groupOp: 'AND',
groups: [],
rules: []
};
filters.groups.push(group);
for (j = 0, l = parts.length; j < l; j++) {
str = parts[j];
if (str) {
// skip empty '', which exist in case of two separators of once
group.rules.push({
data: parts[j],
op: rule.op,
field: rule.field
});
}
}
rules.splice(i, 1);
i--; // to skip i++
}
}
}
this.p.postData.filters = JSON.stringify(filters);
}
};
//TODO: search is filtering in the grid but only from start date and either ge or le start date based on which is first in the column
//TODO: (cont)model. Need to see why end date is not picking up from function.
function invoiceDateSearch($subGrid) {
var postData = $subGrid.getGridParam("postData");
// If there is no post data for some reason, get outta here
if (!postData) {
return;
}
// Make sure the filters object is constructed
var field = "InvoiceDate";
if (!postData.filters) {
postData.filters = {
groupOp: "AND",
rules: []
}
} else {
postData.filters = jQuery.jgrid.parse(postData.filters);
// Need to clear out existing invoice date rules
for (var i = postData.filters.rules.length - 1; i >= 0; i--) {
if (postData.filters.rules[i].field === field) {
postData.filters.rules.splice(i, 1);
}
}
}
var dateRangeString = $("#gs_InvoiceDate").val();
if (dateRangeString.length > 0) {
var dateRange = dateRangeString.split("-");
var startDate = dateRange[0];
var endDate;
if (dateRange.length == 1) {
endDate = dateRange[0];
} else {
endDate = dateRange[1];
}
postData.filters.rules.push({ "field": field, "op": "ge", "data": startDate.trim() });
postData.filters.rules.push({ "field": field, "op": "le", "data": endDate.trim() });
postData.filters = JSON.stringify(postData.filters);
// Need to set the grid's search to true, not the postData's
$subGrid.setGridParam({ search: true });
$subGrid.trigger("reloadGrid", [{ current: true, page: 1 }]);
}
}
function paymentDateSearch($subGrid) {
var postData = $subGrid.getGridParam("postData");
// If there is no post data for some reason, get outta here
if (!postData) {
return;
}
// Make sure the filters object is constructed
var field = "PaymentDate";
if (!postData.filters) {
postData.filters = {
rules: []
}
} else {
postData.filters = jQuery.jgrid.parse(postData.filters);
// Need to clear out existing invoice date rules
for (var i = postData.filters.rules.length - 1; i >= 0; i--) {
if (postData.filters.rules[i].field === field) {
postData.filters.rules.splice(i, 1);
}
}
}
var dateString = $("#gs_PaymentDate").val();
if (dateString.length > 0) {
var startDate = dateRange[0];
postData.filters.rules.push({ "field": field, "op": "eq", "data": startDate.trim() });
postData.filters = JSON.stringify(postData.filters);
// Need to set the grid's search to true, not the postData's
$subGrid.setGridParam({ search: true });
$subGrid.trigger("reloadGrid", [{ current: true, page: 1 }]);
}
}
//**TO overwrite jquery.ui icons and use fontAwesome. extending allows for customization of fA icons set as default in grid**//
$.extend(true, $.jgrid.icons.fontAwesome, {
common: "fa",
sort: {
common: "fa-sort fa-lg"
//asc: "fa-sort",
//desc: "fa-sort"
},
nav: {
common: "fa",
refresh: "fa-recycle fa-lg"
}
});
//**TOOLTIP ADD ON**//
$("[title]").qtip({
position: {
my: "bottom center",
at: "top center",
viewport: $(window)
}
});
//**PRIMARY GRID**//
$grid.jqGrid({
url: "VendInvoice/Vendor",
datatype: "local",
data: gridData,
colNames: ["ID", "Vendor Number", "Vendor Name", "dba", "VendorDbaCombo"],
colModel: [
{ key: true, name: "ID", width: 0, hidden: true, sortable: false, search: false },
{
key: false,
title: false,
name: "VendorNo",
index: "VendorNo",
width: 100,
sortable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["cn"],
attr: { title: "Enter all or part of a Vendor Number." },
clearSearch: false
}
},
{
key: false,
title: false,
name: "VendorName",
//index: "VendorName",
width: 500,
sortable: true,
search: true,
clearSearch: false,
stype: "text",
searchoptions: {
sopt: ["cn"],
clearSearch: false, //removes X in column filters
attr: {
title: "Enter a Vendor Name. SEARCHTIP: Once you start typing, you will begin returning filtered data. To broaden results returned provide less information, to narrow results provide more.",
maxlength: 9080,
dataInit: function (elem) {
$(elem).width(600);
}
}
}
},
{
key: false,
title: false,
name: "Dba",
index: "Dba",
width: 500,
sortable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["cn"],
attr: { title: "Enter all or part of a dba." },
clearSearch: false
}
},
{ key: false, name: "VendorDbaCombo", index: "VendorDbaCombo", width: 1, hidden: true }
],
//**PRIMARY GRID PROPERTIES**//
cmTemplate: { autoResizable: true, editable: true },
iconSet: "fontAwesome",
hidegrid: false,
forceFit: true,
caption: "Vendor Results",
ignoreCase: true,
gridview: true,
autoencode: true,
pager: "#Pager",
toppager: true,
rowNum: 25,
rowList: [5, 10, 25],
autowidth: true,
height: "auto",
viewrecords: true,
loadonce: true,
sortName: "VendorName",
sortOrder: "ASC",
viewsortcols: [true, "vertical", true],
forceClientSorting: true,
multiselect: true,
setGridWidth: 980,
loadtext: "Fetching your data, back in a jiff!",
emptyrecords: "There were no records, try narrowing your search criteria",
loadComplete: function () {
$(this).find(">tbody>tr.jqgrow:visible:odd").addClass("myAltRowClass");
},
onSelectRow: function (row_id) {
$grid.jqGrid("toggleSubGridRow", row_id);
if (row_id !== lastSel && typeof lastSel !== "undefined") {
$grid.jqGrid("setRowData", row_id, false, "myNormal");
}
$grid.jqGrid("setRowData", row_id, false, "myBold");
lastSel = row_id;
},
//**SET SUBGRID**//
subGrid: true,
subGridOptions: {
plusicon: "fa fa-plus-square-o",
minusicon: "fa fa-minus-square-o",
reloadOnExpand: false,
expandOnLoad: false,
delayOnLoad: 50
},
jsonReader: {
id: "id",
root: "rows",
total: "total",
records: "records",
subgrid: {
root: "rows",
repeatitems: true, //must be true in subgrid and false in main grid
cell: ""
}
},
subGridRowExpanded: function (subgrid_id, row_id) {
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id + "_t";
var selectedrow = $(this).jqGrid('getRowData', row_id);
pager_id = "p_" + subgrid_table_id;
var stat = function (subgrid_id, row_id) {
$("#vGrid2").jqGrid("setSelection", "row_id"); //Test to set selection for toggle
}
//**SUBGRID**//
$("#" + subgrid_id).html("<table id='" + subgrid_table_id + "'class='scroll'></table><div id='" + pager_id + "'class='scroll'></div>");
$("#" + subgrid_table_id).jqGrid({
url: "VendInvoice/VendInvoiceSubGridData?vendorID=" + row_id,
datatype: "local",
data: subgridData[rowId],
postData: {
vendorID: row_id,
},
colNames: ["vendorID", "Invoice Status", "Invoice No", "Invoice Date", "Invoice Amount($)", "Payment Date", "Check or ACH Number", "Check or ACH Amount($)", "Encashment Date"],
colModel: [
{ name: "vendorID", key: true, index: "vendorID", hidden: true, width: 0 },
{
name: "InvoiceStatus",
title: false,
index: "InvoiceStatus",
width: 140,
sortable: true,
search: true,
formatter: "select",
stype: "select",
searchoptions: {
sopt: ["cn"],
attr: { title: "If part of your search criteria, select an invoice status from the drop-down menu." },
value: ":Select (All);Paid:Paid;Processing for Payment:Processing for Payment;Reviewing:Reviewing"
}
},
{
name: "InvoiceNo",
title: false,
index: "InvoiceNo",
width: 125,
sortable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["cn", "eq"],
attr: { title: "Enter all or part of an invoice number." },
clearSearch: false
}
},
{
name: "InvoiceDate",
title: false,
index: "InvoiceDate",
width: 135,
formatter: "date",
formatoptions: { srcformat: "m/d/Y", newformat: "m/d/Y" },
jsonmap: function (obj) {
var d = new Date(parseInt(obj.matchstartDate, 10));
return d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()
},
sortable: true,
sorttype: "date",
editable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["ge", "le"],
clearSearch: false,
attr: { title: "Click in the box to open the date range picker." },
dataInit: function (elem) {
$(elem).daterangepicker({
dateFormat: 'mm/dd/yy',
changeYear: true,
changeMonth: true,
todayHighlight: true,
});
//ranges: {
// "Yesterday": [moment(), subtract(1, 'days'), moment().subtract(1, 'days')],
// "Last 7 days": [moment().subtract(6, 'days'), moment()],
// "Last Month": [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
// "This YTD": [moment().startOf('year'), moment().endOf('year')],
// "LastYear": [moment().subtract(1,'year').startOf('year'), moment.subtract(1,'year').endOf('year')]
// }
$(document).on('apply.daterangepicker', function () {
var $subGrid = $("#" + subgrid_table_id);
invoiceDateSearch($subGrid);
});
}
}
},
{
name: "InvoiceAmount",
title: false,
index: "InvoiceAmount",
width: 95,
sortable: true,
sorttype: "float",
formatter: "currency",
formatoptions: {
//prefix: "$",
suffix: "", thousandsSeparator: ",", decimalPlaces: 2
},
search: true,
stype: "text",
searchoptions: {
sopt: ["eq"],
attr: { title: "Enter an invoice amount." },
clearSearch: false
}
},
{
name: "PaymentDate",
title: false,
index: "PaymentDate",
width: 135,
formatter: "date",
formatoptions: { srcformat: "m/d/Y", newformat: "m/d/Y" },
jsonmap: function (obj) {
var d = new Date(parseInt(obj.matchstartDate, 10));
return d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate()
},
sortable: true,
sorttype: "date",
editable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["eq"],
clearSearch: false,
attr: { title: "Click in the box to open the date range picker." },
dataInit:
function (el) {
$(el).datepicker({
dateFormat: 'mm/dd/yy',
changeYear: true,
changeMonth: true,
todayHighlight: true,
orientation: "bottom",
immediateUpdates: true,
autoclose: true
}).on('changeDate', function () {
var $subGrid = $("#" + subgrid_table_id);
paymentDateSearch($subGrid);
$subGrid.setGridParam({ search: true });
$subGrid.trigger("reloadGrid", [{ current: true, page: 1 }]);
});
}
}
},
{
name: "PaymentNo",
title: false,
index: "PaymentNo",
width: 115,
sortable: true,
search: true,
stype: "text",
searchoptions: {
sopt: ["cn", "eq"],
attr: { title: "Enter all or part of a Check or ACH Number." },
clearSearch: false
}
},
{
name: "CheckAmount",
title: false,
index: "CheckAmount",
width: 95,
sortable: true,
sorttype: "float",
formatter: "currency",
formatoptions: { suffix: "", thousandsSeparator: ",", decimalPlaces: 2 },
search: true,
stype: "text",
searchoptions: {
sopt: ["eq"],
attr: { title: "Enter a payment amount." },
clearSearch: false
}
},
{
name: "EncashmentDate",
title: false,
index: "EncashmentDate",
width: 100,
sortable: true,
sorttype: "date",
formatter: "date",
formatoptions: { srcformat: "m/d/Y", newformat: "m/d/Y" },
search: false
}
],
//**SUBGRID PROPERTIES**//
cmTemplate: {
align: "center",
autoResizeable: true
},
idPrefix: "_s",
iconSet: "fontAwesome",
loadonce: true,
loadtext: "Grabbing those invoice, this may take a second!",
autoencode: true,
toppager: true,
autowidth: true,
sortable: true,
showOneSortIcon: true,
autoResizing: { widthOfVisiblePartOfSortIcon: 13 },
viewsortcols: [true, "vertical", true],
multiselect: true,
height: "auto",
rowNum: 500,
rowList: [25, 50, 100, 250, 500],
gridview: true,
viewrecords: true,
emptyrecords: "There were no records, try narrowing your search criteria",
prmNames: {
id: "vendorID"
},
pager: "#" + pager_id,
loadComplete: function () {
$(this).find(">tbody>tr.jqgrow:visible:odd").addClass("myAltRowClass2");
},
beforeSelectRow: function () {
return false;
}
});
jQuery("#" + subgrid_table_id).jqGrid("navGrid", "#" + pager_id, {
edit: false,
add: false,
del: false,
search: true,
refresh: true,
refreshtext: "Refresh Invoice Results",
cloneToTop: true
},
{},
{},
{},
{
multipleSearch: true,
});
jQuery("#" + subgrid_table_id).jqGrid("navButtonAdd", "#" + pager_id, {
caption: "Export to Excel",
buttonicon: "fa-file-excel-o",
onClickButton: function (e) {
exportData(e, "#" + subgrid_table_id);
},
position: "last"
});
jQuery("#" + subgrid_table_id).jqGrid("filterToolbar", {
stringResult: true,
searchOnEnter: false,
ignoreCase: true,
autoSearch: true,
autosearchDelay: 1000,
attr: {
style: "width: auto;padding:0;max-width:100%"
},
defaultSearch: "cn",
//beforeSearch: function () {
// var $subGrid = $("#" + subgrid_table_id);
// invoiceDateSearch($subGrid);
// $subGrid.trigger("reloadGrid", [{ current: true, page: 1 }]);
//}
});
$("[title]").qtip({
position: {
my: "bottom center",
at: "top center",
viewport: $(window)
}
});
var names = [
"Invoice Status", "Invoice No", "Invoice Date", "Invoice Amount", "Payment Date",
"Check or ACH No", "Check or ACH Amount", "Encashment Date"
];
var mydata = [];
var i, j;
if (mydata != null) {
for (i = 0; i < mydata.length; i++) {
mydata[i] = {};
for (j = 0; j < mydata[i].length; j++) {
mydata[i][names[j]] = mydata[i][j];
}
}
}
for (var i = 0; i <= mydata.length; i++);
$("#" + subgrid_table_id).jqGrid('addRowData', i + 1, mydata[i]);
}
}).jqGrid("navGrid", "#Pager", {
edit: false,
add: false,
del: false,
search: false,
refresh: true,
refreshtext: "Refresh Results",
cloneToTop: true
}).jqGrid("filterToolbar", {
stringResult: true,
searchOnEnter: false,
ignoreCase: true,
autoSearch: true,
autosearchDelay: 1000,
attr: {
style: "width: auto;padding:0;max-width:100%"
},
defaultSearch: "cn",
beforeSearch: function () {
modifySearchingFilter.call(this, " ");
}
}).jqGrid("gridResize");
//**TOOLTIP ADD ON**//
$("[title]").qtip({
position: {
my: "bottom center",
at: "top center",
viewport: $(window)
}
});
//**HIDE 'SELECT ALL' CHECKBOX** call after grid is loaded//
$("#cb_" + $grid[0].id).hide();
$("#vGrid2").jqGrid("hideCol", "subgrid");
//**CUSTOM TOOLTIP TEXT FOR COLUMN HEADERS IN PRIMARY GRID**//
var setTooltipsGrid = function (grid, iColumn, text) {
var thd = jQuery("thead:first", grid[0].grid.hDiv)[0];
jQuery("tr.ui-jqgrid-labels th:eq(" + iColumn + ")", thd).attr("title", text);
};
$(".hasTooltip").each(function () {
$(this).qtip({
content: {
text: $(this).next("div")
}
});
});
//setTooltipsGrid($("#vGrid2"), 0, "If exporting, ensure ONLY the row you wish to export is selected. Remove any unnecessary checks in this column.");
//**EXPORT TO EXCEL-CSV**//
function exportData(e, row_id) {
var subGrid = jQuery(row_id).getDataIDs(); // Get all the ids in array
var label = jQuery(row_id).getRowData(subGrid[0]); // Get First row to get the labels
var selRowIds = jQuery(row_id).jqGrid('getGridParam', 'selarrrow');
var obj = new Object();
obj.count = selRowIds.length;
if (obj.count) {
obj.items = new Array();
var elem;
for (elem in selRowIds) {
if (selRowIds.hasOwnProperty(elem)) {
obj.items.push(jQuery(row_id).getRowData(selRowIds[elem]));
}
}
var json = JSON.stringify(obj);
JSONToCSVConvertor(json, "csv", 1);
}
}
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData.items[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.items.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData.items[i]) {
row += '"' + arrData.items[i][index].replace(/(<([^>]+)>)/ig, '') + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//*** FORCE DOWNLOAD ***//
//will generate a temp "a" tag
var link = document.createElement("a");
link.id = "lnkDwnldLnk";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
var csv = CSV;
var blob = new Blob([csv], { type: 'text/csv' });
var myURL = window.URL || window.webkitURL;
var csvUrl = myURL.createObjectURL(blob);
var filename = 'UserExport.csv';
jQuery("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
jQuery('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
});
It seems to me that the usage of custom operation is the best approach to solve your problem. Of cause you can use beforeSearch callback of filterToolbar to modify the filter, but it's too low level operation and it will not work in Searching Dialog.
I would recommend you to read the wiki article which describes the feature. It provides an example with "numeric IN" operation, which you can easy modify to your requirements. The filter callback get in options all the information which you need and the callback should just verify that the data of the testing item (options.item) are inside of interval provided by the value from the date range picker (options.searchValue). I think that you will get small code, which solves your problem, in the way.
Final remark: I'd recommend you to upgrade to the latest 4.13.0 version which fix some bugs, improves performance in some cases and provides new features described in the readme.

how to go to new line in kendo grid with enter key press

here i have developed a web application in mvc4 razor using some kendo ui widgets.in my appication there is a kendo grid which has used to view, update and insert records.
when i press the "add new record" button in grid, inserting a new record will available and with the press of "enter key" i can go to next cell(next column) of the current row.
it will help to insert data in each cell and go to next cell just pressing enter key without clicking each column(with the low number of mouse clicks).
but my next challenge is i need to go to next row(a new record) when i press the enter key at the last cell(last column) of the current row.
here is the code of grid and script i'm using.
<button class="k-button" id="batchGrid">
Batch Edit</button>
<div id="example" class="k-content">
<div id="batchgrid">
</div>
</div>
<script>
$("#batchGrid").click(function () {
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true} },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
UnitsInStock: { type: "number", validation: { min: 0, required: true} }
}
}
}
});
$("#batchgrid").kendoGrid({
dataSource: dataSource,
dataBound: onDataBound,
navigatable: true,
filterable: true,
pageable: true,
height: 430,
width: 300,
toolbar: ["create", "save", "cancel"],
columns: [
{ field: "ProductID", title: "No", width: "90px" },
{ field: "ProductName", title: "Product Name" },
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "130px" },
{ command: ["destroy"], title: " ", width: "175px" }
// { field: "", title: "No", template: "#= ++record #", width: "30px" },
],
editable: { mode: "incell", createAt: "bottom" }
});
});
</script>
<script type="text/javascript">
function onDataBound(e) {
$("#batchgrid").on("focus", "td", function (e) {
var rowIndex = $(this).parent().index();
var cellIndex = $(this).index();
$("input").on("keydown", function (event) {
if (event.keyCode == 13) {
$("#batchgrid")
.data("kendoGrid")
.editCell($(".k-grid-content")
.find("table").find("tbody")
.find("tr:eq(" + rowIndex + ")")
.find("td:eq(" + cellIndex + ")")
.next()
.focusin($("#batchgrid")
.data("kendoGrid")
.closeCell($(".k-grid-content")
.find("table")
.find("tbody")
.find("tr:eq(" + rowIndex + ")")
.find("td:eq(" + cellIndex + ")")
.parent())));
return false;
}
});
});
}
</script>
but the problem is when i press the enter key at the last cell of any row it will not give me a new record(new line).
please help me here..
I'm having same issue, I was able to create new row with enter key press, but the problem is on the page, when ever I press enter key, its creating a new row in the grid, which is not desired. I need to filter the event say for example when the grid is in focus. but I'm not being able to do that yet. Here is my code:
$(document.body).keypress(function (e) {
if (e.keyCode == 13) {
var grid = $("#grid").data("kendoGrid");
grid.addRow();
}
});
If you can set the filter, it will work fine. Let me know if you can sort it out. Thanks.

Kendo Grid equivalent of onEditComplete

Is there an event equivalent to onEditComplete for Kendo Grid where the event fires only after the content of the cell has been edited?
Documentation mentions "edit" event, but this fires as soon as the cell goes into edit mode (So this is equivalent to onBeginEdit).
The closest event with the desired behavior I found was the "save" event, but this event only fires when the content of the cell has been changed. I want an event that fires as soon as the cell goes out of the edit mode.
The grid's editmode is set to incell.
Use the Save event
(fired when the focus is moved outside of the cell being edited and
before the cell is closed)
http://www.kendoui.com/forums/kendo-ui-web/grid/is-there-an-event-that-first-after-a-user-edits-a-cell-but-before-they-save-in-a-grid-with-batch-edit-and-incell-editing-.aspx.
So due to the comment i've removed my previous answer - using the blur event on the input boxes (or other elements) seems to work :
On the grid.edit event, use jquery to bind to the textbox (or any other inline edit control)'s blur event which is fired when focus is lost. Append this to the grid definition...and obviously replace the alert with your code.
edit: function (e) {
alert('Edit Fired');
$('input.k-input.k-textbox').blur(function () {
alert('blur event called');
});
},
I've tested this by modifying the sample inline edit code here
My full local source of the edit - see only the edit event on the grid def:
<div id="example" class="k-content">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1 } },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
toolbar: ["create"],
// added in hook to here to bind to edit element events.
// blur is fired when an element loses focus
edit: function (e) {
alert('Edit Fired');
$('input.k-input.k-textbox').blur(function (e) {
alert('blur event called');
});
},
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "100px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "100px" },
{ field: "Discontinued", width: "100px" },
{ command: ["edit", "destroy"], title: " ", width: "172px" }],
editable: "inline"
});
});
</script>
</div>
Why are you not using the "blur" event?
http://www.kendoui.com/forums/ui/window/possible-to-close-window-when-it-loses-focus-.aspx
$("#window").blur(function(){
if ($(document.activeElement).closest(".k-window").length == 0) {
$("#window").data("kendoWindow").close();
}
});
http://api.jquery.com/blur/
Have you tried the Change Event
"change
Fired when the user selects a table row or cell in the grid."
Example - get the selected data item(s) when using cell selection
<div id="grid"></div>
<script>
function grid_change(e) {
var selectedCells = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedCells.length; i++) {
var dataItem = this.dataItem(selectedCells[i].parentNode);
if ($.inArray(dataItem, selectedDataItems) < 0) {
selectedDataItems.push(dataItem);
}
}
// selectedDataItems contains all selected data items
}
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" }
],
dataSource: [
{ name: "Jane Doe", age: 30 },
{ name: "John Doe", age: 33 }
],
selectable: "multiple, cell"
});
var grid = $("#grid").data("kendoGrid");
grid.bind("change", grid_change);
</script>

Categories

Resources