Feb 08, 2011

jqGrid: Drag and Drop columns (Reordering) with Javascript Array

jqGrid is a jQuery plugin that provides solutions to present and manipulate tabular data and display datagrid based on HTML,CSS and Javascript. I see many articles related to column reorder but all are based on server side data. So I decided to write on jqgrid column reordering based on javascript array data and retrieve data after column reordering.

HTML Structure:

<table id="gridMain"></table>
<div id="pagernav"></div>
<div id="testData"></div>
<input type="button" id="btnGetData" value="GetData" />

JS and CSS files structure:

<link rel="stylesheet" type="text/css" media="screen" href="http://trirand.com/blog/jqgrid/themes/redmond/jquery-ui-1.8.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="http://trirand.com/blog/jqgrid/themes/ui.jqgrid.css" />	

<script src="http://trirand.com/blog/jqgrid/js/jquery.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="http://trirand.com/blog/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>

Our object is to click on header column and try to move it to another location. This feature depend on jQuery UI sortable widget. you must include the "sortable" javascript for jQuery UI. Here it is included in jquery-ui-1.8.1.custom.min.js. You can get it here.

Create A Grid:

var mydata=[

    datatype: "local",
    data: mydata,
    pager: '#pagernav',
	sortname: 'id', 
	sortorder: "desc", 
    sortable: true,
    height: 150,
    colNames: ['Inv No', 'Client', 'Amount', 'Tax', 'Total'],
colModel:[ {name:'id',index:'id', width:40, sorttype:"int"}, 
 {name:'name',index:'name', width:70},
 {name:'amount',index:'amount', width:80, align:"right",sorttype:"float",formatter:"number"},
 {name:'tax',index:'tax', width:80, align:"right",sorttype:"float"},
 {name:'total',index:'total', width:80,align:"right",sorttype:"float"}],   	
    caption: "Manipulating Array Data"
jQuery("#gridMain").jqGrid('navGrid', '#pagernav', {add:false,edit:false,del:false});

This is done again just with setting one options - sortable.

Retrieve data:

You can use $('#gridMain').jqGrid('getRowData') to get reordered data.

See following code to show reordered data on button clicking.

$("#btnGetData").click(function ()
var latestData = $('#gridMain').jqGrid('getRowData');
var record,tbl = '<table style="border:2px solid gray" cellspacing="0" cellpadding="3" >';
for (row in latestData){
record = latestData[row];
tbl += '<tr>';
for (cell in record)
tbl += '<td style="border:1px solid gray"> ' +record[cell] + '</td>';
tbl += '</tr>';
tbl += '</table>';

Hope, It helps.