jqGrid: jQuery - Add class to cell in row - jqgrid

How to add cell-red class to 'pesel' column in row?
{ name: 'pesel', index: 'pesel', width: 220, sortable: true, resizable: false},
{ name: 'differentpesel', index: 'differentpesel', hidden: true, width: 100, sortable: true }
],
(...)
afterInsertRow: function (rowid, rowdata, rowelem) {
if (rowdata.differentpesel == true) {
$('#' + rowid).children('td').addClass('cell-red');
}
}

One should use cellattr instead of afterInsertRow. It allows to add conditionally class or style attribute on some cells of specific column. See here or here for more details.

Related

jqgrid - dynamically change mask based on a previous column value

I am using jquery.maskedinput-1.3.js
In column 1, are the phone types. In column 2 the phone numbers.
{ name: 'PhoneTypeId', index: 'PhoneTypeId', hidden: true, editable: true, sortable: true},
{ name: 'Phone', index: 'Phone', width: 150, editable: true, editoptions: { dataInit: function (elem) { $(elem).mask("(999) 999-9999"); }, dataEvents: [{ type: 'change', fn: function (e) { hasChanges=true } }]}, editrules:{required: true}, sortable: true },
I'd like to dynamically change the mask based on the type of phone. Is this possible?
My data is json serialized objects:
datatype: "local",
data: #Html.Raw(ViewBag.Phones)
editurl: 'clientArray'
Thanks,
Gen
You can add change event (using dataInit) of the phone type and based on this you can change the mask (if this plugin allows this). Initially when you start editing (depending on the edit type - form edit or inline edit) you can use some events before editing by example beforeShowForm for form edit or beforeEditRow for inline edit. If you use Guriddo jqGrid JS you can look at the documentation here
EDIT:
In case the field phonetype is not editable by the user then
{ name: 'Phone', index: 'Phone', width: 150, editable: true,
editoptions:{
dataInit: function (elem, options) {
// use the id of the row
var id = options.rowId;
// content of the phonetype cell
var phonetypeval = $(this).jqGrid('getCell', id, 'PhoneTypeId')
if( phonetypeval === 'something') {
mask = 'mask1';
} else {
mask = 'mask2';
}
$(elem).mask(mask);
},
dataEvents: [{
type: 'change', fn: function (e) { hasChanges=true } }
]}
, editrules:{required: true},
sortable: true}
Note that this code is valid for inline and form edit.

How to make JqGrid always have empty row at bottom?

I'm using JqGrid with inline editing and i dont use navigation, pager or footer. I want to add empty row at the bottom to added. I mean empty row will be always there after editing an exsiting row, after adding new row.
I added row in loadComplete event, but i just adds empty row at beginning not anymore.
jQuery("#tableContents").jqGrid({
postData: { orderId: '139358' },
mtype: "POST",
url: "test.asmx/GetContents",
datatype: "json",
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: { repeatitems: true, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
colNames: ['Master Content ID', 'Description Of Goods', 'No Of Items', 'Total Value for Customs', 'Weight', 'Track No'],
colModel: [
{
name: 'master_content_id', index: 'master_content_id', width: 60, hidden: true, editable: true, editrules: { edithidden: false }
},
{
name: 'content', index: 'content', width: 60, sorttype: "string", editable: true, edittype: "text",
editrules: {
required: true
}
},
{
name: 'piecesInt', index: 'piecesInt', width: 90, align: "right", sorttype: "int", editable: true,
editrules: {
number: true,
required: true
}
},
{
name: 'value', index: 'value', width: 100, align: "right", sorttype: "float", editable: true,
editrules: {
required: true
}
},
{
name: 'weight', index: 'weight', width: 80, align: "right", sorttype: "float", editable: true,
editrules: {
required: true
}
},
{
name: 'track_no', index: 'track_no', width: 80, align: "right", sorttype: "string", editable: true
},
],
rowNum: 10,
rowList: [10, 20, 30],
//pager: jQuery('#pager1'),
sortorder: "desc",
viewrecords: true,
regional: 'tr',
height : '100%',
caption: "Manipulating Array Data",
editurl: 'test.asmx/EditContent',
loadonce: true,
sortable: true,
//footerrow: true,
onSelectRow: function (rowid) {
var $self = $(this),
// savedRows array is not empty if some row is in inline editing mode
savedRows = $self.jqGrid("getGridParam", "savedRow");
if (savedRows.length > 0) {
$self.jqGrid("restoreRow", savedRows[0].id);
}
$self.jqGrid("editRow", rowid, {
keys: true,
extraparam: { orderId: '139358', staffId : '111' },
aftersavefunc: function (rowid) {
alert("Saved");
}
});
},
loadComplete: function () {
var $self = $(this)
$self.jqGrid('addRowData', undefined, {});
}
});
How can we do that?
You try to use jqGrid in the way which is opposite to the standard behavior. It's very bad idea. You will have to write a lot of code and have minimal difference to the standard way.
The main problem is: jqGrid hold data inside of the grid. You try to add an empty row inside of the data which is not loaded from the server, which is not in editing mode (like addRow do for example) and which is not saved on the server. So you try to use the grid in the way contradicting to jqGrid logic. It sounds simple, but it is really bad and the implementation will be complex.
I would recommend you to follow the standard way. You will have clean and simple code and the most of the users can use the grid intuitive. For example you can do add navigator toolbar where you add "+"/"Add" button with respect of inlineNav. The user will intuitively understand what need be done to add new row. The difference whether the user clicks on empty row at the bottom of the grid or if the user clicks on "Add new row" button, existing also at the bottom of the grid, is very small. After the click on the button the new row will be added and the user can insert the data. By press of Enter the row will be saved and by press on Esc the empty row will be removed. The code will be simple and it will do almost the same what you try to implement now.

JqGrid Assigning Custom id to rows and cells

How can I assign the custom id's to JQGrid row and cells. I am using datatype: "local". Is there some thing to do with key in _columnModel_.
You need not to declare any ID to cell , instead you can use name property as ID. To access cell data you can use name property defined in colModel.
You can define your colModel like this:
colModel: [{ name: 'myname', index: 'myname', width: 100, align: 'left', editable: false, search: true },
{ name: 'roll', index: 'roll', width: 100, align: 'left', editable: false, search: false, true}
],
...
And to access row details you can use below codes in onCellSelect method...
,onCellSelect: function (rowid, iCol, cellcontent, target)
{
var rowData = $(this).jqGrid("getRowData", rowid);
var g_myName = rowData.myname;
}

MVC3 Razor Page using jqGrid not rebinding

I have a jqGrid on a view page and it is loaded based on gathering data from a few select lists.
The first time through all is fine. If I change one of the select lists the .change function is triggered but the .jqGrid doesnt fire so the Controller method isnt hit.
My jqGrid code
$("#Builds").change(function () {
var programID = $("#ProgramID").val();
var buildID = $('#Builds').val();
$("#UpdateBuild").show();
// Set up the jquery grid
$("#jqTable").jqGrid({
// Ajax related configurations
url: '#Url.Action("_CustomBinding")',
datatype: "json",
mtype: "POST",
postData: {
programID: programID,
buildID: buildID
},
// Specify the column names
colNames: ["Assembly ID", "Assembly Name", "Cost", "Order", "Budget Report", "Partner Request", "Display"],
// Configure the columns
colModel: [
{ name: "AssemblyID", index: "AssemblyID", width: 40, align: "left", editable: false },
{ name: "AssemblyName", index: "AssemblyName", width: 100, align: "left", editable: false },
{ name: "AssemblyCost", index: "AssemblyCost", width: 40, align: "left", formatter: "currency", editable: true },
{ name: "AssemblyOrder", index: "AssemblyOrder", width: 30, align: "left", editable: true },
{ name: "AddToBudgetReport", index: "AddToBudgetReport", width: 40, align: "left", formatter: "checkbox", editable:true, edittype:'checkbox'},
{ name: "AddToPartnerRequest", index: "AddToPartnerRequest", width: 45, align: "left", formatter: "checkbox", editable:true, edittype:'checkbox'},
{ name: "Show", index: "Show", width: 20, align: "left", formatter: "checkbox", editable:true, edittype:'checkbox'}],
// Grid total width and height and formatting
width: 650,
height: 200,
altrows: true,
// Paging
toppager: true,
pager: $("#jqTablePager"),
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true, // Specify if "total number of records" is displayed
emptyrecords: 'No records to display',
// Default sorting
sortname: "AssemblyID",
sortorder: "asc",
// Grid caption
caption: "Build Template"
}).navGrid("#jqTablePager",
{ refresh: true, add: true, edit: true, del: true },
{}, // settings for edit
{}, // settings for add
{}, // settings for delete
{sopt: ["cn"]} // Search options. Some options can be set on column level
);
});
My controller Code:
[HttpPost]
public JsonResult _CustomBinding(string programID, string buildID, int page, int rows)
{
/* Variable Declarations */
BuildsRepository br = new BuildsRepository();
IEnumerable<ProgramsAssemblyBuilds> pab = br.GetProgramAssembliesBuilds(Convert.ToInt32(programID), Convert.ToInt32(buildID));
// Calculate the total number of pages
var totalRecords = pab.Count();
var totalPages = (int)Math.Ceiling((double)totalRecords / (double)rows);
var data = (from s in pab
select new
{
AssemblyID = s.AssemblyID,
cell = new object[] { s.AssemblyID, s.AssemblyName, s.AssemblyCost, s.AssemblyOrder, s.AddToBudgetReport, s.AddToPartnerRequest, s.Show}
}).ToArray();
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = data.Skip((page - 1) * rows).Take(rows)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Anyone have any ideas on this one?
Thanks
You should create the grid only once. So you should place the code
$("#jqTable").jqGrid({ ... });
outside of the change event handler.
To reload the grid you should use
$("#Builds").change(function () {
$("#jqTable").trigger("reloadGrid", [{page: 1}]);
$("#UpdateBuild").show();
});
At the end to have actual values from "#ProgramID" and '#Builds' you should use functions (methods) as the programID and buildID properties of postData:
// Set up the jquery grid
$("#jqTable").jqGrid({
// Ajax related configurations
url: '#Url.Action("_CustomBinding")',
datatype: "json",
mtype: "POST",
postData: {
programID: function() { return $("#ProgramID").val(); },
buildID: function() { return $('#Builds').val(); }
},
...
});
See more information here.

Bug in populating dropdown on clicking the row in a jqGrid

I want to populate a jqGrid cell dropdownlist when I click the row. I am clicking the row but the dropdownlist isn't getting populated.
The code which I have written for populating the dropdownlist on edit or clicking the row is:
colModel: [
{ name: 'Emp_code', width: 50, sortable: false, align: "center" },
{ name: 'Emp_name', width: 200, sortable: false },
//{ name: 'totalhours', width: 100, sortable: false, align: 'center', editable: true, edittype: "select", editoptions: { value: "1:1;2:2;3:3;4:4;5:5;6:6;7:7;8:8;9:9"} }
{name: 'totalhours', index: 'totalhours', width: 100, sortable: false, align: 'center', editable: true, edittype: "select",
editoptions:
{
dataInit: function(elem) {
$(elem).empty()
.append($('<option></option>').val("1").html("Apples"))
.append($('<option></option>').val("2").html("Oranges"));
}
}
}
],
I want to populate the totalhours column on row click which would populate with apple and oranges, but somehow I am getting blank dropdowns. On row click the dropdown is shown but it's not populated.
If you need to get options item of select from the server you should use editoptions dataUrl and optionally buildSelect. If the server return JSON instead of HTML fragment like
<select><option value="1">Apples</option><option value="2">Oranges</option></select>
one can use buildSelect to convert the server response to the format. If the srever return JSON formatted string your implementation of buildSelect event handler can convert JSON string to the object and then construct the string <select>...</select> from the object.
You can find the corresponding code example for example here.
accordint to ur suggestion i did this ..
colModel: [
{ name: 'Emp_code', width: 50, sortable: false, align: "center" },
{ name: 'Emp_name', width: 200, sortable: false },
//{ name: 'totalhours', width: 100, sortable: false, align: 'center', editable: true, edittype: "select", editoptions: { value: "1:1;2:2;3:3;4:4;5:5;6:6;7:7;8:8;9:9"} }
{name: 'totalhours', width: 100, sortable: false, align: 'center', editable: true, edittype: "select",
editoptions: { dataUrl: '../Services/ServiceTest.asmx/GetListHours',
buildSelect: function(data) {
alert('hello i am here ');
var response = jQuery.parseJSON(data.responseText);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
var ri = response[i];
s += '<option value="' + ri + '">' + ri + '</option>';
}
}
return s + "</select>";
}
}
}
],
and the corresponding webserivce i which i am calling for is :
public String GetListHours()
{
List<int> list = new List<int> { };
for (int i = 0; i < 10; i++)
{
list.Add(i);
}
return JsonConvert.SerializeObject(list);
}
but still when i am clicking the row the dropdownlist is showing blank... is there any event which should i cal through ? that should be fired when i am clicking a row ? to populate the dropdownlist ? above is the code which i tried to implement according to ur suggestion . but it seems like it doesnt even calling the dataurl to populate cause the function alert is not firing at all

Resources