w2ui grid on jquery-ui tab: issue on rendering - jquery-ui

I have a page containing 2 tabs (built with jquery-ui).
My need is to display 2 different w2ui grid (one for each tab) but the second one is shown as partial/truncated:
$(function() {
$('#tabs').tabs({
heightStyle: "fill"
});
let grid1 = new w2grid({
name: 'grid1',
box: '#grid1',
columns: [
{ field: 'recid', text: 'ID', size: '50px', sortable: true, attr: 'align=center' },
{ field: 'lname', text: 'Last Name', size: '30%', sortable: true },
{ field: 'fname', text: 'First Name', size: '30%', sortable: true },
{ field: 'email', text: 'Email', size: '40%' },
{ field: 'sdate', text: 'Start Date', size: '120px' }
],
records: [
{ recid: 1, fname: 'Jane', lname: 'Doe', email: 'jdoe#gmail.com', sdate: '4/3/2012' },
],
})
let grid2 = new w2grid({
name: 'grid2',
box: '#grid2',
columns: [
{ field: 'recid', text: 'ID', size: '50px', sortable: true, attr: 'align=center' },
{ field: 'lname', text: 'Last Name', size: '30%', sortable: true },
{ field: 'fname', text: 'First Name', size: '30%', sortable: true },
{ field: 'email', text: 'Email', size: '40%' },
{ field: 'sdate', text: 'Start Date', size: '120px' }
],
records: [
{ recid: 2, fname: 'Stuart', lname: 'Motzart', email: 'jdoe#gmail.com', sdate: '4/3/2012' },
],
})
})
<link href="https://rawgit.com/vitmalina/w2ui/master/dist/w2ui.min.css" rel="stylesheet"/>
<script src="https://rawgit.com/vitmalina/w2ui/master/dist/w2ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id='tabs'>
<ul>
<li><a href='#grid1'>Grid1</a></li>
<li><a href='#grid2'>Grid2</a></li>
</ul>
<div id='grid1'>This is Grid1</div>
<div id='grid2'>This is Grid2</div>
</div>
This is the result:
#grid1 on tab1 is show correctly:
#grid2 on tab2 is show truncated (2 fields are shown out of 5 instead):
Does anyone see something wrong in the grid (or tabs?) definition?

The issue is dependent by the visibile area when the grid is populated. Being the 2nd tab hidden, the grid is truncated to the 2nd field.
The workaround I've found is to grab the 'activate' event on tab click and to trigger a w2ui[ grid ].reload() event in addition with the override of '#grid_whatever_toolbar' height forced to 52px:
$('#tabs').tabs({
heightStyle: 'fill',
activate: function(event ,ui){
reports[ui.newTab.index()].report;
w2ui[ reports[ui.newTab.index()].report ].reload()
$('#grid_' + reports[ui.newTab.index()].report + '_toolbar').css({ 'height' : '52px' });
}
})
It's almost a dirty solution but it works. Any suggestion of improvement is more than welcome.

Related

jqxgrid print formatting and missing column

I have a jqxgrid that gets data from a DB. i have added a run time column call Serial number. This shows on the grid alright. Also on the grid is a print button. The print button when clicked opens a new window with the print preview, but in the preview it does not show the Sr. Numbers.
Pls have a look at the code below and if you can lead me in the right direction.
Thanks
<div id='jqxWidget' style="font-size: 13px; font-family: Verdana; float: left;">
<div id="jqxgrid"></div>
<div style='margin-top: 20px;'>
<div style='float: left;'>
<input type="button" value="Print" id='Print' />
</div>
</div>
var data = generatedata(100);
var source = {
localdata: data,
datatype: "array",
datafields: [{
name: 'firstname',
type: 'string'
}, {
name: 'lastname',
type: 'string'
}, {
name: 'productname',
type: 'string'
}, {
name: 'available',
type: 'bool'
}, {
name: 'quantity',
type: 'number'
}, {
name: 'price',
type: 'number'
}],
updaterow: function (rowid, rowdata) {
// synchronize with the server - send update command
}
};
var dataAdapter = new $.jqx.dataAdapter(source);
// initialize jqxGrid
$("#jqxgrid").jqxGrid({
width: 700,
source: dataAdapter,
theme: 'energyblue',
editable: true,
selectionmode: 'singlecell',
columns: [
{
text: '#', sortable: false, filterable: false, editable: false,
groupable: false, draggable: false, resizable: false,
datafield: '', columntype: 'number', width: 30,
cellsrenderer: function (row, column, value) {
return "<div style='margin:4px;'>" + (value + 1) + "</div>";
}
},
{
text: 'First Name',
columntype: 'textbox',
datafield: 'firstname',
width: 90
}, {
text: 'Last Name',
datafield: 'lastname',
columntype: 'textbox',
width: 90
}, {
text: 'Product',
datafield: 'productname',
width: 170,
}, {
text: 'Price',
datafield: 'price',
cellsalign: 'right',
cellsformat: 'c2',
width: 100
}]
});
$("#Print").jqxButton({
theme: 'energyblue'
});
$("#Print").click(function () {
var prnt = $("#jqxgrid").jqxGrid('exportdata', 'html');
var newWindow = window.open('', '', 'width=800, height=500'),
document = newWindow.document.open(),
pageContent =
'<!DOCTYPE html>\n' + '<html>\n' + '<head>\n' + '<meta charset="utf-8" />\n' + '<title>Summary</title>\n' + '</head>\n' + '<body>\n' +
'<div>\n<div id="image1" style="position:absolute; overflow:hidden; left:3px; top:3px; width:160px; float:left;">\n' +
'</div>\n<div style="margin-left: 300px;float:left;top:5px;"><h2>Sums</h2></div>\n' +
'</div>\n<br /><br /><br /><br />' + prnt + '\n</body>\n</html>';
document.write(pageContent);
newWindow.print();
});
});
here is a working sample. But i am not sure how to make the button work.
https://jsfiddle.net/Vinod1/by6duep4/3/

jQuery-JTable: add on click event for row?

I have to following code to show my user table, this is achieved by JTable.
<script type="text/javascript">
$(document).ready(function() {
$('#userTableContainer').jtable({
title: 'Users',
selecting: false,
paging: true,
pageSize: 15,
sorting: true,
addRecordButton: false,
saveUserPreferences: false,
create: false,
edit: false,
actions: {
listAction: 'user/getUsers.htm',
},
fields: {
username: {
title: 'username'
},
firstname: {
title: 'firstname'
},
lastname: {
title: 'lastname'
},
company: {
title: 'company'
}
}
});
$('#userTableContainer').jtable('load');
});
</script>
<div id="content">
<h1>Users</h1>
<br />
<div id="userTableContainer">
</div>
</div>
Is it possible to add a custom action event for every row?
So that i could submit a request like "user/showUser.htm" to my controller.
This should get you on your way:
$('#userTableContainer').jtable({
....
recordsLoaded: function(event, data) {
$('.jtable-data-row').click(function() {
var row_id = $(this).attr('data-record-key');
alert('clicked row with id '+row_id);
});
}
});

asp.net mvc jqgrid submit grid using a button outside of the grid

I'm new to jqgrid and MVC. My Jqgrid is in multi select mode, and I want to submit all selected items on the grid to the controller by clicking on a button (tbrSave) outside of the grid.
#using (Html.BeginForm("Save", "Home"))
{
<button type="submit" id="tbrSave" class="toolbar">
<span title="Config" class="icon-32-save"></span>Save</button>
<script src="#Url.Content("~/Scripts/grid.locale-en.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.jqGrid.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.custom.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var lastSelectedRow;
$('#jqGridCategoryCreate').jqGrid({
//url from wich data should be requested
url: 'CategoriesList',
//type of data
datatype: 'json',
editurl: '#Url.Action("UpdateCategory")',
//url access method type
mtype: 'POST',
//columns names
colNames: ['CategoryId', 'Category Name', 'Display Order', 'Is Featured Product'], //columns model
colModel: [
{ name: 'Id', index: 'Id', align: 'left', editable: false },
{ name: 'Name', index: 'Name', align: 'left', editable: false },
{ name: 'DisplayOrder', index: 'DisplayOrder', align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 10 }, editrules: { required: true} },
{ name: 'IsFeaturedProduct', index: 'IsFeaturedProduct', align: 'left', editable: true, edittype: 'text', edittype: 'checkbox', editoptions: { maxlength: 10, value: '1:Yes;0:No' }, formatter: 'checkbox', editrules: { required: true}}],
//pager for grid
pager: $('#jqPagerCategoryCreate'),
//number of rows per page
rowNum: 10,
//initial sorting column
sortname: 'Id',
//initial sorting direction
sortorder: 'asc',
//we want to display total records count
viewrecords: true,
multiselect: true,
//grid width
width: 'auto',
//grid height
height: 'auto',
ondblClickRow: function (id) {
if (id && id != lastSelectedRow) {
//save changes in row
jQuery('#jqGridCategoryCreate').saveRow(lastSelectedRow);
$.lastSelectedRow = id;
//trigger inline edit for row
$('#jqGridCategoryCreate').editRow(lastSelectedRow, true);
}
}
});
$('#jqGridCategoryCreate').jqGrid('navGrid', '#jqPagerCategoryCreate',
{ add: false, del: true, edit: false, search: false },
{ width: 'auto', url: '/Category/Edit' },
{ width: 'auto', url: 'SaveCustomLanguageData' },
{ width: 'auto', url: '/Category/Delete' });
function getSelectedRows() {
//make sure all items must be in view mode before submitting.
jQuery('#jqGridCategoryCreate').saveRow(lastSelectedRow);
var rows = $("#jqGridCategoryCreate").jqGrid('getGridParam', 'selarrrow');
var categories = [];
$.each(rows, function (index, rowId) {
var gridRow = $("#jqGridCategoryCreate").getRowData(rowId);
var category = { "Id": rowId,
"DisplayOrder": gridRow['DisplayOrder']
};
categories.push(category);
});
}
});
</script>
}
How can I attach getSelectedRows to the grid in order to post it to Controller ("Save").
Thanks a mil.
Nam Vo.
This would involve following steps
1) Create a anchor link on your razor view
<a id="somelink" href="">Select Multiple Accounts</a>
2) Create a click event handler for anchor link created above
$('#somelink').click(function () {
var multiplerowdata = jQuery("#grid").getGridParam('selarrrow');
$.ajax({ type: 'POST',
url: '#Url.Action("YourController", "YourActionMethod")',
data: JSON.stringify(multiplerowdata),
traditional: true,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { alert("row submited"); }
});})
3) At times you may get javascript error of JSON is not defined, this can be solved by inserting meta tags in shared\_layout.cshtml page as shown below
<meta http-equiv="X-UA-Compatible" content="IE=8" />
4) YourActionMethod inside YourController should like be somewhat like this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult YourActionMethod(List<string> datarow)
{
//return "sucessfully validated";
return null;
}

How to enable excel export button for jqGrid

Hello
I want to show "export to excel" button in the pager of jqgrid. I tried many ways, read many articles/posts, but I don't see this button. Documentation does not have anything useful too. Which actions should I do to see this button
Ps. I use ASP.NET MVC
PSS. my code is
<link href="../../Scripts/jquery.UI/css/redmond/jquery-ui-1.8.1.custom.css" rel="Stylesheet"
type="text/css" />
<link href="../../Scripts/jquery.jqGrid/css/ui.jqgrid.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/i18n/grid.locale-ru.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/jquery.jqGrid.min.js"></script>
<table id="EmployeeTable">
</table>
<div id="EmployeeTablePager">
</div>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('#EmployeeTable').jqGrid({
url: '/Employee/EmployeeData',
datatype: "json",
mtype: 'POST',
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
repeatitems: false,
id: ""
},
colNames: ['Id', 'Имя', 'Фамилия', 'Email', 'Date'],
colModel: [
{ name: 'Id', width: 20 },
{ name: 'FirstName', width: 105 },
{ name: 'LastName', width: 100 },
{ name: 'Email', width: 150 },
{ name: 'Date', width: 150, formatter: ndateFormatter }
],
pager: '#EmployeeTablePager',
excel: true,
viewrecords: true
}).jqGrid('navButtonAdd',
'#EmployeeTablePager',
{ caption: " Export to Excel ",
buttonicon: "ui-icon-bookmark",
onClickButton: genCSV, position: "last"
});
});
function genCSV() {
alert('a');
}
function ndateFormatter(cellval, opts, rwdat, _act) {
var time = cellval.replace(/\/Date\(([0-9]*)\)\//, '$1');
var date = new Date();
date.setTime(time);
return date.toDateString();
}
</script>
but I don't see the excel import button.
http://ru.magicscreenshot.com/jpg/t97BDzCIO0Q.html
why?
Assuming markup of
<table id="jqgrid"></table>
<div id="pager"></div>
Something along the lines of
$('#grid')
.jqGrid({
datatype: "clientSide",
height: 190,
colNames: headers,
colModel: model,
multiselect: true,
pager: '#pager',
pgbuttons: false,
pginput: false,
caption: "Random Data",
deselectAfterSort: false,
width: 930
})
.jqGrid('navButtonAdd',
'#pager',
{caption:" Export to Excel ",
buttonicon:"ui-icon-bookmark",
onClickButton: genCSV, position:"last"});
genCSV will be a JavaScript function that will make the call to the controller action to generate a CSV file.
Here's an example, in combination with jQuery flot. Create some data, select some grid rows and then click the generate graph button in the bottom left of the grid to plot the points. Note that this will not work in Internet Explorer less than 8 as it requires support for the HTML 5 canvas element (and I haven't bothered to include excanvas).
EDIT:
Your markup is not working because you need to initialize a navGrid before being able to set a custom button (see note on page). You can do this like so
jQuery(document).ready(function () {
jQuery('#EmployeeTable').jqGrid({
url: '/Employee/EmployeeData',
datatype: "json",
mtype: 'POST',
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
repeatitems: false,
id: ""
},
colNames: ['Id', 'Имя', 'Фамилия', 'Email', 'Date'],
colModel: [
{ name: 'Id', width: 20 },
{ name: 'FirstName', width: 105 },
{ name: 'LastName', width: 100 },
{ name: 'Email', width: 150 },
{ name: 'Date', width: 150, formatter: ndateFormatter }
],
pager: '#EmployeeTablePager',
excel: true,
viewrecords: true
})
/* Need to initialize navGird before being able to set any custom buttons */
.jqGrid('navGrid', '#EmployeeTablePager', {
add: false,
edit: false,
del: false,
search: false,
refresh: false
}).jqGrid('navButtonAdd',
'#EmployeeTablePager',
{ caption: " Export to Excel ",
buttonicon: "ui-icon-bookmark",
onClickButton: genCSV, position: "last"
});
});
function genCSV() {
alert('a');
}
function ndateFormatter(cellval, opts, rwdat, _act) {
var time = cellval.replace(/\/Date\(([0-9]*)\)\//, '$1');
var date = new Date();
date.setTime(time);
return date.toDateString();
}
What I did was to create a csv file on the server and display a download link next to the grid in my view.
It's not as slick as what you have in mind but it is quick and easy to implement.
Extension method to create a csv file from a list (from another post on SO):
public static string AsCsv<T>(this IEnumerable<T> items)
where T : class
{
var csvBuilder = new StringBuilder();
var properties = typeof(T).GetProperties();
foreach (T item in items)
{
//string line = properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray().Join(",");
string line= string.Join(", ", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
csvBuilder.AppendLine(line);
}
return csvBuilder.ToString();
}
private static string ToCsvValue<T>(this T item)
{
if (item is string)
{
return string.Format("\"{0}\"", item.ToString().Replace("\"", "\\\""));
}
double dummy;
if (double.TryParse(item.ToString(), out dummy))
{
return string.Format("{0}", item.ToString());
}
return string.Format("\"{0}\"", item.ToString());
}
Controller:
model.AListOfData.ToArray().AsCsv();
using (StreamWriter sw = System.IO.File.CreateText(errorFilePath))
{
sw.Write(values);
}
model.ErrorFullFileName = errorFilePath;
In the view:
<%=Html.ImageLink("", "AssetUpload", "DownloadErrors", "/?filename=" + Model.ErrorFullFileName, "/Content/Icons/excel.png", "Download errors and warnings", "imagelink")%>
I used this and it works pretty well
jQuery("#table_resultats").jqGrid('navGrid', "#yourpager").jqGrid( //#pager
'navButtonAdd', "#yourpager", {
caption : "Excel export",
buttonicon : "ui-icon-arrowthickstop-1-s",
onClickButton : null,
position : "first",
title : Excel export,
cursor : "pointer"
});

Multiple jQgrids in jQueryui Tabs

I am having an issue that I need help with. I have 3 jQueryUI Tabs. The first holds a grid of items. The second holds a grid of Work Orders. The third just fires an alert to verify the show function is working. Problem is I have no grid on the second tab. First one loads fine. If I comment out the code for the first tab, the second grid shows up fine. Third tab fires an alert every time. I have a lightbox that i use to edit items on select which works fine. Here's the relevant code:
jQuery(document).ready(function () {
$('#tabs').tabs({
show: function(event, ui) {
if(ui.index == 0)
{
jQuery("#list1").jqGrid({
...
pager: '#pager1',
...
jQuery("#list1").jqGrid('navGrid','#pager1',{edit:false,add:false,del:false});
}
else if(ui.index == 1)
{
$("#list").jqGrid({
...
pager: '#pager',
....
onSelectRow: function(id){
if(id){
alert(id);
onclick=openbox('Edit Work Order', 1);
...
else if(ui.index == 2)
{
alert('tab2');
}
}
I appreciate any help you can give.
Probably your problem exist because you used the HTML code
<div id="tabs-1">
<table id="list1"><tr><td/></tr></table>
<div id="pager1"/>
</div>
<div id="tabs-2">
<table id="list"><tr><td/></tr></table>
<div id="pager"/>
</div>
<div id="tabs-3">
<p>Bla bla</p>
</div>
instead of
<div id="tabs-1">
<table id="list1"><tr><td/></tr></table>
<div id="pager1"></div>
</div>
<div id="tabs-2">
<table id="list"><tr><td/></tr></table>
<div id="pager"></div>
</div>
<div id="tabs-3">
<p>Bla bla</p>
</div>
I modified you code a little to the following
jQuery(document).ready(function () {
var initGrids= [false,false];
$('#tabs').tabs({
show: function (event, ui) {
if (ui.index === 0 && initGrids[ui.index] === false) {
jQuery("#list1").jqGrid({
url: 'fillgrid.php',
datatype: 'json',
mtype: 'GET',
colNames: ['serial', 'type', 'origin', 'subtype', 'refreshdate'],
colModel: [
{ name: 'id', index: 'id', width: 55 },
{ name: 'type', index: 'type', width: 90 },
{ name: 'origin', index: 'origin', width: 80, align: 'right' },
{ name: 'subtype', index: 'subtype', width: 80, align: 'right' },
{ name: 'refreshdate', index: 'refreshdate', width: 80, align: 'right' }
],
pager: '#pager1',
rowNum: 10,
rowlist: [10, 20, 30],
sortname: 'id', // NOT 'serial',
sortorder: 'desc',
viewrecords: true,
caption: 'CPE Items',
width: 950
});
jQuery("#list1").jqGrid('navGrid', '#pager1', { edit: false, add: false, del: false });
initGrids[ui.index] = true;
}
else if (ui.index === 1 && initGrids[ui.index] === false) {
$("#list").jqGrid({
url: 'fillgridwo.php',
datatype: 'json',
mtype: 'GET',
colNames: ['Job Number', 'Date', 'System', 'Status', 'Technician', 'Timeframe'],
colModel: [
{ name: 'id', index: 'id', width: 55 },
{ name: 'Date', index: 'date', width: 90 },
{ name: 'System', index: 'wsystem', width: 80, align: 'right' },
{ name: 'Status', index: 'status', width: 80, align: 'right' },
{ name: 'Technician', index: 'wname', width: 80, align: 'right' },
{ name: 'Timeframe', index: 'time', width: 80, align: 'right' }
],
pager: '#pager',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id', // NOT 'jobno' or 'Job Number'
sortorder: 'desc',
viewrecords: true,
caption: 'Work Orders',
width: 950,
onSelectRow: function (id) {
//var d;
if (id) {
alert(id);
//??? onclick = openbox('Edit Work Order', 1);
//??? d = "jobno=" + id;
$.ajax({
url: 'fillwo.php',
type: 'POST',
dataType: 'json',
data: {jobno:id},
success: function (data) {
var id;
for (id in data) {
if (data.hasOwnProperty(id)) {
$(id).val(data[id]);
}
}
}
});
$("button, input:submit").button();
}
jQuery('#list').editRow(id, true);
}
});
jQuery("#list").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
initGrids[ui.index] = true;
}
else if (ui.index === 2) {
alert('tab2');
}
}
});
});
I included array initGrids which will be used to initialize every grid only once, commented unclear code like onclick = openbox('Edit Work Order', 1); and fixed sortname.
You can see the demo. The grid contain will be not filled, because I not have any server components on the server
I know its an old question. But I also faced the same issue where in I had multiple jqGrids under the tabs and the loading thing was not working.
Adding the below code in the javascript just before defining the grid worked for me:
$('#Grid').jqGrid('GridDestroy');
For me, the grids on different tabs where the same only the data inside the grid was changing.

Resources