JqGrid, how to center delete box? - javascript

in My Jqgrid i have a column with delete links, everything works perfect, except that delete confirmation box pops up at top left corner all the time. i want to have the confirmation box in center of the jqgrid, not in top left corner.
{ name: 'act', index: 'act', width: 150, align: 'center', sortable: false}],
gridComplete: function () {
var rows = jQuery("#list").jqGrid('getGridParam','selrow');
var ids = jQuery("#list").jqGrid('getDataIDs');
var gr = jQuery('#list'); gr.setGridHeight("auto", true);
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<a href='#' style='height:25px;width:120px;' type='button' value='Slet' onclick=\"jQuery('#list').jqGrid('delGridRow','" + cl + "',{reloadAfterSubmit:false, url:'#Url.Action("deleteRow")'}); return false;\">Slet </>";
jQuery("#list").jqGrid('setRowData', ids[i], { act: be });
}
},
UPDATE
be = "<a href='#' style='height:25px;width:120px;' type='button' value='Slet' onclick=\"jQuery('#list').jqGrid('delGridRow','" + cl + "', myDelParameters); return false;\">Slet </>";
code for my Global variable:
myDelParameters = {reloadAfterSubmit:false, url:'#Url.Action("deleteRow")', beforeShowForm: function(form) {
// "editmodlist"
var dlgDiv = jQuery("#list").jqGrid("#delmodlist" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// TODO: change parentWidth and parentHeight in case of the grid
// is larger as the browser window
dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";
}};

You set already some parameters of the delGridRow method (see {reloadAfterSubmit:false, url:... in your code).
My suggestion that you use afterShowForm in the list of delGridRow parameters. The implementation of the afterShowForm could be like in the old answer, but with the usage of "#delmodlist" ("#delmod" + grid[0].id, where var grid = $("#list")) instead of $("#editmod" + grid[0].id).
Another more short form of the implementation could be with respect of jQuery UI Position:
afterShowForm = function ($form) {
$form.closest('div.ui-jqdialog').position({
my: "center",
of: $("#list").closest('div.ui-jqgrid')
});
}
In the demo I use such function for all Add/Edit and Delete forms.
UPDATED: It seems to me that you have implementation problems. I made one more demo which you can easy modify to what you want. I don't set any editurl, so if you press "Delete" button the error will be displayed. Moreover the HTML fragment which you try to place in the 'act' column is a combination of <a> and <button> settings. Because I don't know what you wanted I placed just <a> in the 'act' column. I hope now you can easy modify my demo to make your program working.
Here is the schema of the code from my demo which you can use:
<script type="text/javascript">
//<![CDATA[
var myDelParameters = {
reloadAfterSubmit: false,
//url:'#Url.Action("deleteRow")',
afterShowForm: function ($form) {
'use strict';
$form.closest('div.ui-jqdialog').position({
my: "center",
of: $("#list").closest('div.ui-jqgrid')
});
}
};
$(document).ready(function () {
var grid = $("#list"),
centerForm = function ($form) {
$form.closest('div.ui-jqdialog').position({
my: "center",
of: grid.closest('div.ui-jqgrid')
});
},
getColumnIndexByName = function (mygrid, columnName) {
var cm = mygrid.jqGrid('getGridParam', 'colModel'), i = 0, l = cm.length;
for (; i < l; i += 1) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
};
grid.jqGrid({
colModel: [
...
{name: 'action', index: 'action', width: 70, align: 'center', sortable: false},
...
],
...
loadComplete: function () {
var iCol = getColumnIndexByName($(this), 'action'), iRow, row,
rows = this.rows,
cRows = rows.length;
for (iRow = 0; iRow < cRows; iRow += 1) {
row = rows[iRow];
if ($.inArray('jqgrow', row.className.split(' ')) > 0) {
$(row.cells[iCol]).html("<a href='#' style='height:25px;width:120px;' onclick=\"jQuery('#list').jqGrid('delGridRow','" +
row.id + "',myDelParameters); return false;\">Del</>");
}
}
});
});
//]]>
</script>

for centering the jqdialog and display near the row selected
.ui-jqdialog{position:fixed; left:415px;}
This is working perfect for my requirement.
Thank You

Related

Widget that add or subtract one day from each date of a column in kendo grid

I would like to create a widget for each column of my kendo grid that can add or subtract one day from each date of that specific column. These are the columns
initGridReparti: function initGridReparti() {
var gridColumns = [
{
field: "repartoDescr",
title: "Reparto",
width: 200
},
{
field: "dataAtt",
title: "Data Attivazione",
format:"{0:dddd dd MMM yyyy}",
width:100
},
{
field: "dataChimpdv",
title: "Data Chiusura Impegni PDV",
format:"{0:dddd dd MMM yyyy}",
width: 100
},
{
field: "dataChimpsede",
title: "Data Chiusura Impegni Sede",
format:"{0:dddd dd MMM yyyy}",
width: 100
},
{
field: 'statoPubblicazioneERP',
title: 'Stato pubblicazione ERP',
attributes: { 'class': 'align-center' },
width: 100,
template: function (dataItem) {
//var sezioneDescr = _.get(_.find(this._filters.dataSources.sezioniVolantinoCurrentPromo, 'id', dataItem.sezioneId), 'descrizione', '');
var statoPubblicazioneERPId = _.get(dataItem, 'statoPubblicazioneERP', 1);
var statoPubblicazioneERPCode = commonLookupData.getItemCodeById(constants.commonLookupDataNames.statiPubblicazione, statoPubblicazioneERPId);
var statoPubblicazioneERPDescr = commonLookupData.getItemDescrById(constants.commonLookupDataNames.statiPubblicazione, statoPubblicazioneERPId);
return '' +
'<span class="ff-item ajax-loading" data-id-reparto="' + dataItem.repartoId + '"><img src="img/ajaxLoading2.gif" /></span> ';
}.bind(this),
},
];
I would like to add these widgets below each column.
Can you help me to understand how can I do that?
Here is what I came up with. You will need to make use of a footer template(https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/configuration/columns.footertemplate). In this template let's say you have 2 buttons. You can use whatever you want and style it how you want. What is important here are the events.
<button class="subtract-btn" data-column-id="Column1">−</button>
<button class="add-btn" data-column-id="Column1">&plus;</button>
Now set up some JQuery to handle the events like so. Of course this assumes the date you are trying to change is bound to the column. In this case that date is called Column1
$(document).ready(function () {
$('#grid').on('click', '.subtract-btn', subtractDate);
$('#grid').on('click', '.add-btn', addDate);
});
function subtractDate(e) {
var columnId = $(this).data('columnId');
var data = $('#grid').data('kendoGrid').dataSource.data();
var dataLen = data.length;
var item, columnValue;
for (var i = 0; i < dataLen; i++) {
item = data[i];
columnValue = item[columnId];
columnValue.setDate(columnValue.getDate() - 1); //I prefer to use momentjs
item.set(columnId, columnValue); //Forces UI update
}
}
function addDate(e) {
var columnId = $(this).data('columnId');
var data = $('#grid').data('kendoGrid').dataSource.data();
var dataLen = data.length;
var item, columnValue;
for (var i = 0; i < dataLen; i++) {
item = data[i];
columnValue = item[columnId];
columnValue.setDate(columnValue.getDate() + 1); //I prefer to use momentjs
item.set(columnId, columnValue); //Forces UI update
}
}

JavaScript loop inside tinymce button

My JavaScript loop is not working properly inside a tinymce button.
I set a variable n which is the array size that I get from my html input.
var n = $('#total').val();
Then, I create the array of tinymce buttons: var menuItems = [];
In my tinymce editor init, I create the buttons:
editor.on('init', function (e) {
for (var i=1; i<=n; i++){
var obj = {
text: 'Item ' + i,
onclick: function() {
var msg = ' <strong>#item' + i + '#</strong> ';
editor.insertContent(msg);
}
}
menuItems.push(obj);
}
});
Last step is add the menuItems to the tinymce buttons:
editor.addButton('myButton', {
type: 'menubutton',
text: 'Items',
icon: false,
menu: menuItems
});
The buttons are displaying correct with the correct label. I have the buttons:
Item 1
Item 2
Item 3
However, doesn't matter which button I click, the text displayed in the editor is item3. It always get the last button text.
Does anyone know why it is happening?
Thanks
Use let instead of var since let would keep its lexical block scope where var would not:
editor.on('init', function(e) {
for (let i = 1; i <= n; i++) { // <-- use let here
var obj = {
text: 'Item ' + i,
onclick: function() {
var msg = ' <strong>#item' + i + '#</strong> ';
editor.insertContent(msg);
}
}
menuItems.push(obj);
}
});
Here is the documentation on let

jQuery DataTable - Column level filters on top and fixed height not working together

I am trying to display data in a jQuery DataTable which has column level filter at the top, fixed height and scroller enabled. I am able to display the column level filter at the top and have it working. But, as soon as I set the height (scrollY property), the column level filters at the top disappear.
Fiddler: https://jsfiddle.net/8f63kmeo/6/
HTML:
<table id="CustomFilterOnTop" class="display nowrap" width="100%"></table>
JS
var Report4Component = (function () {
function Report4Component() {
//contorls
this.customFilterOnTopControl = "CustomFilterOnTop"; //table id
//data table object
this.customFilterOnTopGrid = null;
}
Report4Component.prototype.ShowGrid = function () {
var instance = this;
//create the datatable object
instance.customFilterOnTopGrid = $('#' + instance.customFilterOnTopControl).DataTable({
columns: [
{ data: "Description", title: "Desc" },
{ data: "Status", title: "Status" },
{ data: "Count", title: "Count" }
],
"paging": true,
//scrollY: "30vh",
//deferRender: true,
//scroller: true,
dom: '<"top"Bf<"clear">>rt <"bottom"<"Notes">ilp<"clear">>',
buttons: [
{
text: 'Load All',
action: function (e, dt, node, config) {
instance.ShowData(10000);
}
}
]
});
//now, add a second row in header which will hold controls for filtering.
$('#' + instance.customFilterOnTopControl + ' thead').append('<tr role="row" id="FilterRow">' +
'<th>Desc</th>' +
'<th>Status</th>' +
'<th>Count</th>' +
'</tr>');
$('#' + instance.customFilterOnTopControl + ' thead tr#FilterRow th').each(function () {
var title = $('#' + instance.customFilterOnTopControl + ' thead th').eq($(this).index()).text();
$(this).html('<input type="text" onclick="StopPropagation(event);" placeholder="Search ' + title + '" class="form-control" />');
});
$("div.Notes").html('<div class="alert alert-warning">This is a notes section part of the table dom.</div>');
};
Report4Component.prototype.BindEvents = function () {
var instance = this;
$("#CustomFilterOnTop thead input").on('keyup change', function () {
instance.customFilterOnTopGrid
.column($(this).parent().index() + ':visible')
.search(this.value)
.draw();
});
};
Report4Component.prototype.ShowData = function (limit) {
if (limit === void 0) { limit = 100; }
var instance = this;
instance.customFilterOnTopGrid.clear(); //latest api function
var recordList = [];
for (var i = 1; i <= limit; i++) {
var record = {};
record.Description = "This is a test description of record " + i;
record.Status = "Some status " + i;
record.Count = i;
recordList.push(record);
}
instance.customFilterOnTopGrid.rows.add(recordList);
instance.customFilterOnTopGrid.draw();
};
return Report4Component;
}());
$(function () {
var report4Component = new Report4Component();
report4Component.ShowGrid();
report4Component.BindEvents();
report4Component.ShowData();
});
function StopPropagation(evt) {
if (evt.stopPropagation !== undefined) {
evt.stopPropagation();
}
else {
evt.cancelBubble = true;
}
}
Current Status
When the following properties are commented,
//scrollY: "30vh",
//deferRender: true,
//scroller: true,
the table appears with the column level filters on top as shown below,
Issue:
When the above properties are enabled, the column level filter disappears,
You can use the fiddler to see this behavior.
Expectation:
I want to have a DataTable with column level filter on top, fixed height and scroller enabled. What am I missing? Any help / suggestion is appreciated.
You need to use table().header() API function to access thead element instead of referencing it directly. When Scroller or FixedHeader extensions are used thead element appears outside of your table in a separate element.
See updated jsFiddle for code and demonstration.

jqGrid Add Button and Modal

When I click the cancel button in the add modal, I get the following error in the jquery.jqGrid.js file:
"0x800a138f - JavaScript runtime error: Unable to get property 'a' of undefined or null reference"
I only get this error in Internet Explorer, Chrome works fine.
The second issue I am having is that I'm calling the add modal from a button:
<button name="addbutton" id="addbutton" class="add-new-row btn btn-success addbutton" style="float:right; margin-top:1%; margin-left:1%;">Add</button>
and then using the following code in the grid JS file:
$(".addbutton").on("click", function () {
$("#grid").editGridRow("new",
{
// add options
//2lines added by Ilango
top: 50, left: 100, width: 500,
addCaption: "Add record Dialog",
addParams: { position: "afterSelected" },//, addRowParams: editOptions
zIndex: 100,
url: "/Transactions/Create",
closeOnEscape: true,
closeAfterAdd: true,
reloadAfterSubmit: true,
afterComplete: function (response) {
if (response.responseText) {
$('#grid').trigger('reloadGrid')
// alert(response.responseText);
//window.location.reload();
//reDefineColWidth();
// $('#grid').trigger('reloadGrid')
window.history.back();
}
},
//submit on enter key
onInitializeForm: function ($form) {
$("td.DataTD>.FormElement", $form).keypress(function (e) {
if (e.which === $.ui.keyCode.ENTER) {
$("#sData", $form.next()).trigger("click");
return false;
}
});
},
//adjust position of add form modal
beforeShowForm: function (form) {
//alert('adding' + "#editmod" + grdNames[0].id);
//var dlgDiv = $("#editmod" + grdNames[0].id);
var dlgDiv = $("#editmod" + $('#grid')[0].id);
//var dlgDiv = jQuery("#editmodgrid");
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
// HINT: change parentWidth and parentHeight in case of the grid
// is larger as the browser window
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
//400 offset from left
dlgDiv[0].style.left = Math.round(parentLeft + 500 + (parentWidth - dlgWidth) / 2) + "px";
},
afterShowForm: function (form) {
//alert('adding' + "#editmod" + grdNames[0].id);
//var dlgDiv = $("#editmod" + grdNames[0].id);
var dlgDiv = $("#editmod" + $('#grid')[0].id);
//var dlgDiv = jQuery("#editmodgrid");
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
// HINT: change parentWidth and parentHeight in case of the grid
// is larger as the browser window
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
//400 offset from left
dlgDiv[0].style.left = Math.round(parentLeft + 500 + (parentWidth - dlgWidth) / 2) + "px";
},
});
});
When I click the submit button, the record is submitted, but only with the default values I have setup for each column, not the values that I entered into the modal. I don't have this issue using the built in navigation add button.
Please help! I've spent many, many hours trying to figure this out.
EDIT:
Here is the block of code where the error occurs if(!h.a):
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
if(A[0]){A.pop();if(!A[0])L('unbind');}
if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
}

Get all selected ids of jqgrid in external javascript function

I am using multi-select grid functionality in my application and it is working as i expected. But the issue is i need to get all the selected records across the pagination in external javascript function. Below is my code,
function createCommodity(){
$.ajax({
url : 'commoditycategory.do?method=listCommodity' + '&random='
+ Math.random(),
type : "POST",
async : false,
success : function(data) {
$("#list2").jqGrid('GridUnload');
var newdata = jQuery.parseJSON(data);
var wWidth = $(window).width();
var dWidth = wWidth * 0.7;
var wHeight = $(window).height();
var dHeight = wHeight * 0.5, idsOfSelectedRows = [];
jQuery("#list2").jqGrid({
data : newdata,
datatype : "local",
colNames : [ "id", "Commodity Code",
"Commodity Description", "Commodity Category" ],
colModel : [
{
name : 'id',
index : 'id',
hidden : true,
editable : true
},
{
name : 'commodityCode',
index : 'commodityCode',
align : "center",
editable : true,
editrules : {
required : true
}
},
{
name : 'commodityDesc',
index : 'commodityDesc',
align : "center",
editable : true,
editrules : {
required : true
}
},
{
name : 'commodityCategoryId',
index : 'commodityCategoryId',
align : "center",
// hidden : true,
editable : true,
edittype : "select",
editoptions : {
dataUrl : 'commoditycategory.do?method=parentCategory'
+ '&random=' + Math.random()
},
editrules : {
edithidden : true,
required : true
// custom : true
}
} ],
pager : "#pager2",
rowNum : 10,
rowList : [ 10, 20, 50 ],
height : "230",
width : dWidth,
onSelectRow: function (id, isSelected) {
var p = this.p, item = p.data[p._index[id]], i = $.inArray(id, idsOfSelectedRows);
item.cb = isSelected;
if (!isSelected && i >= 0) {
idsOfSelectedRows.splice(i,1); // remove id from the list
} else if (i < 0) {
idsOfSelectedRows.push(id);
}
},
loadComplete: function () {
var p = this.p, data = p.data, item, $this = $(this), index = p._index, rowid, i, selCount;
for (i = 0, selCount = idsOfSelectedRows.length; i < selCount; i++) {
rowid = idsOfSelectedRows[i];
item = data[index[rowid]];
if ('cb' in item && item.cb) {
$this.jqGrid('setSelection', rowid, false);
}
}
},
multiselect : true,
cmTemplate : {
title : false
}
});
$grid = $("#list2"),
$("#cb_" + $grid[0].id).hide();
$("#jqgh_" + $grid[0].id + "_cb").addClass("ui-jqgrid-sortable");
cbColModel = $grid.jqGrid('getColProp', 'cb');
cbColModel.sortable = true;
cbColModel.sorttype = function (value, item) {
return typeof (item.cb) === "boolean" && item.cb ? 1 : 0;
};
}
});
}
Till now its working great. Its holding correct rows which are selected across pagination.
And My external JS function where i need to get the selected rowids include pagination is,
function updateCommodity() {
var grid = jQuery("#list2");
var ids = grid.jqGrid('getGridParam', 'selarrrow'); // This only returns selected records in current page.
if (ids.length > 0) {
var html = "<table id='commodityTable' class='main-table' width='100%' border='0' style='border:none;border-collapse:collapse;float: none;'><thead><td class='header'>Commodity Code</td><td class='header'>Commodity</td><td class='header'>Action</td></thead><tbody>";
for ( var i = 0, il = ids.length; i < il; i++) {
var commodityCode = grid.jqGrid('getCell', ids[i],
'commodityCode');
var commodityDesc = grid.jqGrid('getCell', ids[i],
'commodityDesc');
html = html
+ "<tr class='even' id='row" + i + "'><td><input type='text' name='commodityCode' id='geographicState"+i+"' class='main-text-box' readonly='readonly' value='" + commodityCode + "'></td>";
html = html
+ "<td><input type='text' name='commodityDesc' id='commodityDesc"+i+"' class='main-text-box' readonly='readonly' value='" + commodityDesc + "'></td>";
html = html
+ "<td><a style='cursor: pointer;' onclick='deleteRow(\"commodityTable\",\"row"
+ i + "\");' >Delete</a></td></tr>";
}
html = html + "</tbody></table>";
$("#commodityArea").html(html);
}
}
Update I have fiddled the issue for providing more clarity about the issue.
First of all I want remind that you use the code which I posted in the answer.
I see that the solution of your problem is very easy. The list of options of jqGrid can be easy extended. If you just include new property in the list of options
...
data : newdata,
datatype : "local",
idsOfSelectedRows: [],
...
you will don't need more define the variable idsOfSelectedRows (see the line var dHeight = wHeight * 0.5, idsOfSelectedRows = []; of you code). To access new option you can use
var ids = grid.jqGrid('getGridParam', 'idsOfSelectedRows');
instead of var ids = grid.jqGrid('getGridParam', 'selarrrow');. To make the code of onSelectRow and loadComplete callbacks working with idsOfSelectedRows as jqGrid option you should just modify the first line of the callbacks from
var p = this.p, ...
to
var p = this.p, idsOfSelectedRows = p.idsOfSelectedRows, ...
It's all.
UPDATED: See http://jsfiddle.net/OlegKi/s2JQB/4/ as the fixed demo.

Categories