jqGrid add new column
It is not possible to add a column to the jqGrid dynamically. You have to recreate the whole grid with colModel
having one column more. If you use separate colNames
, then the size of the array have to be increased too. You can use GridDestroy for example to destroy the existing grid. The usage of jQuery.Remove
or jQuery.Empty
instead is also possible.
UPDATED: It seems to me that GridUnload is better for your porpose. I created small demo which demonstrate how one can recreate a grid. To be able to use GridUnload or GridDestroy you have to verify that you include grid.custom.js in your project (if you use developer version of the jqGrid) or you have checked "Custom" "Additinal methods" on the jqGrid download page.
UPDATED 2: One can use addColumn
method which can be downloaded from here (see jQuery.jqGrid.addColumn.js
). The method is still in beta phase. One can find some demos which shows how to use the method here (see addColumnX.htm
examples).
Adding a new column to existing JQ GRID
It's important to understand that jqGrid creates the grid with all internal structures once. jqGrid don't provide a method which allows to add new column. So you have the following alternatives:
- use
GridUnload
to "destroy" the grid back to empty<table>
and recreate the grid with new columns (see the answer) - create grid with additional hidden columns and make hidden column visible using
showCol
when you need to add new column. In the way you will have the same effect as by adding the column.
By the way if you load named property of data in the grid (your JSON input data looks like {"order_id":"123", "name": "abc" , "status": "OK"...}
) you can define colModel
as
colModel: [
{name: "c1", key: true, jsonmap: "order_id"},
{name: "c2", jsonmap: "name"},
{name: "c3", jsonmap: "status"},
...
]
using generic names c1
c2
, c3
, ... for the columns. In the way you can easy modify the value of jsonmap
at the runtime. You can set hidden: true
property or remove it etc. The answer shows how to use beforeProcessing
to modify colModel
based on the server response. In the way you can makes jqGrid full dynamical.
How to add extra column in jqGrid
if you want to add a column dynamically then you need to rebind the grid again
check the link below.
jqGrid add new column
Create a new column with sum of few other columns in jqgrid
The most easy way to implement your requirements would be the usage of jsonmap
and sorttype
defined as function, which returns the calculated value of the column. Additionally you would need to implement afterSetRow
callback, which fixes the value after modification the row (after setRowData
).
The corresponding implementation could be like in the demo. The demo defines the grid with total
column, which displays the sum of amount
and tax
columns. The code of the demo looks as following:
var calculateTotal = function (item) {
return parseFloat(item.amount) + parseFloat(item.tax);
};
$("#list").jqGrid({
...
colModel: [
...
{ name: "amount", template: "number", ... },
{ name: "tax", template: "number", ... },
{ name: "total", width: 76, template: "number", editable: false,
jsonmap: function (item) {
return calculateTotal(item);
},
sorttype: function (cellValue, item) {
return calculateTotal(item);
}},
...
],
afterSetRow: function (options) {
var item = options.inputData;
if (item.total === undefined) {
// test is required to prevent recursion
$(this).jqGrid("setRowData", options.rowid, {
total: calculateTotal(item)
});
}
}
...
});
JQGrid - show additional columns in edit form
If you want to show and not to edit the columns then the usage of viewGridRow as the usage of editGridRow. Moreover I would suggest you to consider to use columnChooser which allows user to hide/show columns of the grid or to change its order. For example you can display in the grid only subset of 30 rows, use navGrid to add View Details button (you need use view: true
option) and use navButtonAdd to add custom button with column chooser. You can additionally makes explicit call of viewGridRow
inside of ondblClickRow
callback. One need add the properties editrules: {edithidden: true}
in the definition of all hidden columns which need be visible/editable in View/Edit/Add forms
The resulting grid can look like on the following demo or like here:
$(function () { "use strict"; var mydata = [ { id: "10", invdate: "2007-10-01", name: "test1", note: "note1", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" }, { id: "20", invdate: "2007-10-02", name: "test2", note: "note2", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }, { id: "30", invdate: "2007-09-01", name: "test3", note: "note3", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" }, { id: "40", invdate: "2007-10-04", name: "test4", note: "note4", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" }, { id: "50", invdate: "2007-10-31", name: "test5", note: "note5", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }, { id: "60", invdate: "2007-09-06", name: "test6", note: "note6", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" }, { id: "70", invdate: "2007-10-04", name: "test7", note: "note7", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" }, { id: "80", invdate: "2007-10-03", name: "test8", note: "note8", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }, { id: "90", invdate: "2007-09-01", name: "test9", note: "note9", amount: "400.00", tax: "30.00", closed: false, ship_via: "TN", total: "430.00" }, { id: "100", invdate: "2007-09-08", name: "test10", note: "note10", amount: "500.00", tax: "30.00", closed: true, ship_via: "TN", total: "530.00" }, { id: "110", invdate: "2007-09-08", name: "test11", note: "note11", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" }, { id: "120", invdate: "2007-09-10", name: "test12", note: "note12", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" } ], $grid = $("#list"), initDateEdit = function (elem) { $(elem).datepicker({ dateFormat: "dd-M-yy", autoSize: true, changeYear: true, changeMonth: true, showButtonPanel: true, showWeek: true }); }, initDateSearch = function (elem) { var $self = $(this); setTimeout(function () { $(elem).datepicker({ dateFormat: "dd-M-yy", autoSize: true, changeYear: true, changeMonth: true, showWeek: true, showButtonPanel: true, onSelect: function () { if (this.id.substr(0, 3) === "gs_") { // call triggerToolbar only in case of searching toolbar setTimeout(function () { $self[0].triggerToolbar(); }, 100); } } }); }, 100); }, numberTemplate = {formatter: "number", align: "right", sorttype: "number", editrules: {number: true, required: true}, searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge", "nu", "nn", "in", "ni"] }};
$grid.jqGrid({ datatype: "local", data: mydata, colNames: ["Client", "Date", "Closed", "Shipped via", "Notes", "Tax", "Amount", "Total"], colModel: [ { name: "name", align: "center", editable: true, width: 65, editrules: {required: true} }, { name: "invdate", width: 80, align: "center", sorttype: "date", formatter: "date", formatoptions: { newformat: "d-M-Y" }, editable: true, datefmt: "d-M-Y", editoptions: { dataInit: initDateEdit }, searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDateSearch } }, { name: "closed", width: 70, align: "center", editable: true, formatter: "checkbox", edittype: "checkbox", editoptions: {value: "Yes:No", defaultValue: "Yes"}, stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;true:Yes;false:No" } }, { name: "ship_via", width: 105, align: "center", editable: true, formatter: "select", edittype: "select", editoptions: { value: "FE:FedEx;TN:TNT;IN:Intim", defaultValue: "IN" }, stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;FE:FedEx;TN:TNT;IN:IN" } }, { name: "note", width: 60, sortable: false, editable: true, edittype: "textarea", hidden: true }, { name: "tax", width: 52, editable: true, template: numberTemplate, hidden: true }, { name: "amount", width: 75, editable: true, template: numberTemplate, hidden: true }, { name: "total", width: 60, template: numberTemplate } ], cmTemplate: {editable: true, editrules: {edithidden: true}}, rowNum: 10, rowList: [5, 10, 20], pager: "#pager", gridview: true, autoencode: true, ignoreCase: true, sortname: "name", viewrecords: true, sortorder: "desc", rownumbers: true, shrinkToFit: false, height: "auto", ondblClickRow: function (rowid) { $(this).jqGrid("viewGridRow", rowid); } }); $.extend($.jgrid.view, { caption: "View Record Details", recreateForm: true }); $grid.jqGrid("navGrid", "#pager", {add: false, edit: false, del: false, search: false, refresh: false, view: true, viewtitle: "View details of selected row" }); $grid.jqGrid("navButtonAdd", "#pager", { caption: "", buttonicon: "ui-icon-calculator", title: "Choose Columns to display in the grid", onClickButton: function () { $(this).jqGrid("columnChooser"); } });});
.ui-jqgrid-hdiv { overflow-y: hidden; }
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/redmond/jquery-ui.css"/><link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/css/ui.jqgrid.css"/><link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/plugins/ui.multiselect.css" /><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script><script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.6.0/plugins/ui.multiselect-fixed.js"></script><script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/js/i18n/grid.locale-en.js"></script><script type="text/javascript"> $.jgrid.no_legacy_api = true; $.jgrid.useJSON = true;</script><script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/js/jquery.jqGrid.src.js"></script><script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.6.0/plugins/jQuery.jqGrid.columnChooser.js"></script>
<table id="list"><tr><td></td></tr></table><div id="pager"></div>
jqGrid dynamic column binding
Try this in document.ready:
$.ajax(
{
type: "POST",
url: "SomeUrl/GetColumnsAndData",
data: "",
dataType: "json",
success: function(result)
{
colD = result.colData;
colN = result.colNames;
colM = result.colModel;
jQuery("#list").jqGrid({
jsonReader : {
cell: "",
id: "0"
},
url: 'SomeUrl/Getdata',
datatype: 'jsonstring',
mtype: 'POST',
datastr : colD,
colNames:colN,
colModel :colM,
pager: jQuery('#pager'),
rowNum: 5,
rowList: [5, 10, 20, 50],
viewrecords: true
})
},
error: function(x, e)
{
alert(x.readyState + " "+ x.status +" "+ e.msg);
}
});
setTimeout(function() {$("#list").jqGrid('setGridParam',{datatype:'json'}); },50);
this work fine for me.
How to add a new column of buttons/images in jqgrid
You don't need to bind click
event handler to every button in the column. Every binding take memory and other resources of web browser. The most events bubbling to from inner to outer DOM element (see here), Mouse click, Keyboard keydown, Touch touchstart and other events on the button inside of grid will be bubble to the grid's <table>
element. jqGrid register by default click
event handler on the grid. It calls beforeSelectRow
and onCellSelect
callbacks and trigger jqGridBeforeSelectRow
and jqGridCellSelect
events from the event handler. So instead of binding your own click
event handlers on every button it's enough to use one from listed above callbacks or events. beforeSelectRow
(or jqGridBeforeSelectRow
) will be used first. The callback is practical if you what that click on the button don't select the corresponding row. The answer for example shows how to verify whether the column which you needs are called. Another answer provides an example which will be very close to what you need. One more answer gives you another code fragment. To see more my old answers about the subject you can use the following query.
UPDATED: the demo http://jsfiddle.net/ShKDX/82/ is modification of the demo posted by Manuel van Rijn. It demonstrates what I mean.
Getting Dynamic Columns in JQGrid
A little search and I found this topic explaining how to do what you want. And here is a demo adding columns dinamically. Basically, what you have to do is: create a function
with the data you want for each of your tabs and insert a click event handler to unload the previous set data and call the function for the specific clicked tab to insert new data in the grid.
Related Topics
How to Implement Jquery.Noconflict()
Ruby Equivalent to JavaScript's Encodeuricomponent That Produces Identical Output
The Best Way to Synchronize Client-Side JavaScript Clock with Server Date
Rails 4 Client Side Validation
Implement JavaScript Alert and Confirm on Wkuidelegate Swiftui
What Is Wkerrordomain Error 4 from Wkwebview
How to Make Regular Expression into Non-Greedy
Is JSON Hijacking Still an Issue in Modern Browsers
Passing Functions to Settimeout in a Loop: Always the Last Value
Escape String - Output Rails String in JavaScript
How to Export Tables to Excel from a Webpage
Sort an Array of Object by a Property (With Custom Order, Not Alphabetically)
Unobtrusive JavaScript: <Script> at the Top or the Bottom of the HTML Code
Difference of the Value, Prototype and Property
Is There a Version of JavaScript's String.Indexof() That Allows for Regular Expressions