Wednesday, December 31, 2014

Fetching Cell value in jqGrid

Let's say we have the following code to render the data in a jqGrid. In this example, we will be using JSON and get the data using webservice. I will not show the details of calling webservice but you can see the details of the application in this Spring Hibernate Integration post.

The code for displaying jqgrid is as follows


<script type="text/javascript">
 $(document).ready(function() {
$("#userListGrid").jqGrid({ 
 url: "<c:url value='/ws/rest/users'/>", 
 datatype: "JSON", 
 mtype: "GET", 
 colNames: ['First Name', 'Last Name', 'Email', 'Role', 'Status'], 
 colModel: [ {name: 'firstName', index: 'firstName', width: 250}, 
             {name: 'lastName', index: 'lastName',  width: 250},
             {name: 'email', index: 'email', width: 250},
             {name: 'role', index: 'role', width: 250},
             {name: 'status', index: 'status', width: 250}],
 sortname: 'First Name', 
 viewrecords: true, 
 sortorder: 'desc', 
 caption: 'Users List'
 });


 });
 </script>

<table id="userListGrid">
   <tr><td></td></tr>
</table>

It's a straight forward code for displaying jqGrid.

Now let's say we want to fetch the value of role column from the grid. For that see the code in yellow background down below. I have put it in a javascript timer so that it gives time to load the jqGrid completely otherwise it will not return the data. If you want to fetch values as part of some action, you can ignore the javascript timer.

<script type="text/javascript">
 $(document).ready(function() {
$("#userListGrid").jqGrid({ 
 url: "<c:url value='/ws/rest/users'/>", 
 datatype: "JSON", 
 mtype: "GET", 
 colNames: ['First Name', 'Last Name', 'Email', 'Role', 'Status'], 
 colModel: [ {name: 'firstName', index: 'firstName', width: 250}, 
             {name: 'lastName', index: 'lastName',  width: 250},
             {name: 'email', index: 'email', width: 250},
             {name: 'role', index: 'role', width: 250},
             {name: 'status', index: 'status', width: 250}],
 sortname: 'First Name', 
 viewrecords: true, 
 sortorder: 'desc', 
 caption: 'Users List'
 });
 setTimeout(function(){
  var ids = jQuery("#userListGrid").getDataIDs(); 
    for(var i=0;i<ids.length;i++){        
      var identifyImg = $('#userListGrid').jqGrid('getRowData', ids[i]);
      var CellValue = $('#userListGrid').jqGrid('getCell', ids[i],'role');
      alert(CellValue); 
   }
}, 2000);

 });
 </script>

<table id="userListGrid">
   <tr><td></td></tr>
</table>

No comments:

Post a Comment