Multiple jQgrids in jQueryui Tabs - jquery-ui

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.

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/

JQgrid custom add a row

i have one button out side of jqGrid. when i click the button it should hit the inside the jqGrid add button. is it possible.
<input type="button" id="btnCustomAdd" value="Add"/>
when i click the above button inside jqGrid button should hit. is it possible.
jqGrid:
$("#Datasourcegrid").jqGrid({
postData: { CAId: function () { return $('#hdnchnAppId').val(); } },
colNames: ['DataSourceId', 'Title','Sort Order'],
colModel: [
{ name: 'DataSourceId', index: 'DataSourceId', align: 'left', key: true, editable: false, hidden: true, search:false,width: '10'},
{ name: 'DataSourceTitle', index: 'DataSourceTitle', sortable: true, align: 'left', width: '400',editable: true, edittype: 'text', editrules: { required: true },stype:'text', search:true,searchoptions:{sopt:['eq']}},
{ name: 'SortOrder', index: 'SortOrder', sortable: true, align: 'left', width: '100',editable: true, hidden: true, edittype: 'text', editrules:{number:true, required:true}, search:false},
],
You can do it this way, if you meant that just new empty row shows
$(function(){
$("#btnCustomAdd").on("click", function(event){
$("#grid").jqGrid("addRowData", rowid, { Id: rowid});
//OR
$("#grid").addRow(rowid, parameters);
//OR new API
$("#grid").jqGrid('addRow',parameters);
//FORM EDIT EXAMPLE
$("#grid").editGridRow( "new", parameters );
//OR new API
$("#grid").jqGrid('editGridRow', "new", parameters );
});
});
parameters =
{
rowID : "new_row",
initdata : {},
position :"first",
useDefValues : false,
useFormatter : false,
addRowParams : {extraparam:{}}
}
EDIT: Added form-edit example you can read more about form editing here

Date-picker in jqGrid, simple example?

Does anyone know of an example of adding the jquery UI DatePicker (or some other perhaps) in the jqGrid? I'm trying to get it to work for an inline edit grid.
I have found a few examples, but nothing works. I would like something really simple!
My Grid setup (don't know if it's nessecary for this question):
$(function () {
var lastsel;
$("#list").jqGrid({
url: '#Url.Action("ExampleData", "Home")',
datatype: 'json',
mtype: 'GET',
colNames: ['Namn', 'Födelsedag', 'Adress', 'Stad'],
colModel: [
{ name: 'Name', index: 'Name', width: 130, editable: true },
{ name: 'Birthday', index: 'Birthday', width: 80, editable: true },
// DatePicker for birthday
{ name: 'Address', index: 'Address', width: 180, editable: true },
{ name: 'City', index: 'City', width: 80, editable: true },
],
pager: '#pager',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'Name',
sortorder: 'desc',
viewrecords: true,
gridview: true,
width: 700,
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('saveRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: '#Url.Action("Incoming", "Home")',
caption: 'Kontaktpersoner'
});
jQuery("#list").jqGrid('navGrid', "#pager", { edit: false, add: false, del: true });
jQuery("#list").jqGrid('inlineNav', "#pager");
As you can read in jqGrid documentation there is a dataInit option for this. What you should remember that this event is raised before the element is inserted into DOM, so use setTimeout just to be safe:
{ name: 'Birthday', index: 'Birthday', width: 80, editable: true editoptions: { dataInit: function(el) { setTimeout(function() { $(el).datepicker(); }, 200); } } },
The simplicity of the code depend of the format of the data which you fill in the 'Birthday' column. What you mostly need is to include
editoptions: { dataInit: function (elem) { $(elem).datepicker(); } }
as additionally property of 'Birthday' column. Sometimes one need define onSelect callback for the datepicker (see here), sometime one need to use setTimeout additionally or make some other customizations (see the answer) which includes working demos.

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"
});

Resources