Creating a custom search option in jqGrid : jQuery

Here’s a way to use custom search in the jQgrid.
I have to search data which is not a part of the result grid.
Hence I have created a separate form to get the search values and post the data using jqGrid to get the result set.

var emp = {
initGrid: function(){
var grid_selector = “#grid-table”;
var pager_selector = “#grid-pager”;

jQuery(grid_selector).jqGrid({
url: “url/to/loaddata”,
datatype: “json”,
mtype: “POST”,
colNames: [“First Name”, “Last Name”, “ID”, “Sex”, “DOB”, “Address”, “Score”],
colModel: [
{ name: “firstname”, width: ’50px’},
{ name: “lastname”, width: ’50px’},
{ name: “ID”, width: ’40px’},
{ name: “sex”, width: ’30px’},
{ name: “birthdate”, width: ’30px’},
{ name: “address”, width: ’60px’},
{ name: “score”, width: ’30px’}
],
height: ‘auto’,
viewrecords : true,
rowNum:10,
rowList:[10,20,30],
pager : pager_selector,
altRows: true,
sortname: ‘firstname’,
sortorder: “asc”,
beforeRequest: function(){
//show custom loader before posting data
commonfn.showPageLoader();
},
loadComplete : function(){
// hide the loader after grid is loaded
commonfn.hidePageLoader();
},
postData:{
‘fname’: function () { return $(“#fname”).val(); },
‘lname’: function () { return $(“#lname”).val(); },
‘id’: function () { return $(“#id”).val(); },
‘score’: function () { return $(“#score”).val(); },
‘oper’: function () { return $(“#oper”).val(); },
‘searchId’: function () { return $(“#searchId”).val(); }
},
caption: “”,
autowidth: true,
loadui: ‘disable’
});
},
searchGrid: function(){
// reload the table with search data
if ($.trim($(“#fname”).val()) == ” && $.trim($(“#lname”).val()) == ” &&

$.trim($(“#id”).val()) == ” && $.trim($(“#score”).val()) == ” &&

$(‘#searchId’).val() == ” ){
commonFn.showNotification(‘Please select atleast one search criteria’);
}else{
$(“#grid-table”).trigger(“reloadGrid”, { page: 1 });
}
},
}
var emp = {
emp.initGrid();
}

Here’s a brief description of what the code does:

initGrid initialises the grid with:

url: ‘url/to/loaddata’ This is a url that makes the db query and returns the result set

postData: This is the most important part.
This specifies what data will be posted when we reload the grid.
So here, we get the values of the search fields and pass them.
Then in the server, make the query with those values and return the result set

searchGrid: This is called on clicking the search button or clear button.
It triggers the “reloadGrid” method of jQuery which loads the grid again.

Hope this post was helpful for you!

Leave a comment