jqGrid Local Data Live Search

jqGrid is an incredibly powerful and flexible plugin for jQuery that allows you to build data grids using nothing but Javascript, HTML, and CSS. I recently wanted to allow live filtering of local results (no AJAX queries, just parsing local data) based on a search string. View the demo and then follow along below.

Basic HTML Structure

Below is some very basic HTML that you can use to build a jqGrid.

<html>
  <head>
    <!--snipped necessary JS and CSS includes here-->
    <title>jqGrid Live Search Demo</title>
  </head>
  <body>
    <h2>jqGrid Live Search Demo</h2>
    <table id="list"></table>
  </body>
</html>

Create A Grid

This snippet will create a grid using the “smoothness” jQuery-UI theme. This grid has 3 columns and obtains its data in JSON format from “data.php”. Notice the global declaration of searchColumn and the call to fetch an array of all the data from the name column when the gridComplete event fires. You could grab the other columns as well, but for this example we’re only going to search on name.

var gridimgpath = 'css/smoothness/images';
var grid = jQuery('#list');
var searchColumn;
 
grid.jqGrid({
	url:'data.php',
	datatype: 'json',
	mtype: 'POST',
	colNames: ['Name','Data','Date'],
	colModel :[ 
	  {name:'name', index:'name', width:140}, 
	  {name:'data', index:'data', width:200},
	  {name:'date', index:'date', width:200},
	],
	sortname: 'date',
	sortorder: 'asc',
	caption:'Search: <input type="search" id="gridsearch" placeholder="Search" results="0" class="gridsearch" />',
	viewrecords: true,
	loadonce: true,
	width: 750,
	forceFit: true,
	height:130,
	gridComplete: function() {
		searchColumn = grid.jqGrid('getCol','name',true) //needed for live filtering search
	}
  });

Live Filtering

This is the simple code that allows us to live filter on the grid. It will hide any id that doesn’t match the string you’re entering. The search is case insensitive.

//for live filtering search
jQuery('#gridsearch').keyup(function () {
	var searchString = jQuery(this).val().toLowerCase()
	jQuery.each(searchColumn,function() {
		if(this.value.toLowerCase().indexOf(searchString) == -1) {
			jQuery('#'+this.id).hide()
		} else {
			jQuery('#'+this.id).show()
		}
	})
})

Known Issues

At the moment if the first row is hidden the grid becomes unaligned from its headers (and live resizing of the columns does not work). This issue can be hidden by making all the headers the same width, but if a user resizes the problem will be visible again. There is a bug open on github to correct the issue.

Leave a comment ?

13 Comments.

  1. Esta muy bueno el ejemplo pero he podido comprobar que no busca en todas las paginas del jqgrid solo busca en la la pagina actual

  2. Puedo ayudarte en el codigo para que busque en varias paginas, estamos a la orden read424_gmail_com
    :!:

  3. Great tutorial, just what I was looking for. I modified the code to search across all columns in the grid:

    // Declare variables

    var grid = $(“#list”);
    var gridData;

    // Grid complete event
    gridComplete: function() {
    gridData = grid.jqGrid(‘getRowData’);
    }

    // The search function
    $(“#search”).keyup(function() {
    var searchString = $(this).val().toLowerCase();
    var rowMatch = false;
    for(row=0; row < gridData.length; row++) {
    rowMatch = false;
    $.each(gridData[row],function(key, value) {
    if(value.toLowerCase().indexOf(searchString) != -1) {
    rowMatch = true;
    return;
    }
    });

    if(rowMatch) {
    $('#'+(row+1)).show();
    } else {
    $('#'+(row+1)).hide();
    }
    }
    });

  4. Great Tip!!!
    Thanks

  5. Wow, this i nice little tip (and thanks Marcin for the contribution). When I first viewed the demo, I was like “wow” but immediately thought, how about searching all columns. Then Marcin contributes.

  6. Wow, this i nice little tip! When I first viewed the demo, I was like “wow” but immediately thought, how about searching all columns. Then Marcin contributes, but alas I cant get his code to work. Anybody have this working searching across all columns?

  7. FWIW, in Marcin code, I can tell the query etc is working but the portion where it hide/show the row, I dont think the jQuery selector is correct. My table construct is

  8. Hi Thanks for sharing.. yep its working with all columns but the problem is its not searching across the pages. Working on that now …

  9. Small fix for code of Marcin if uses id column:
    [code]
    rowId = gridData[row]['id'];
    if (rowMatch) {
    $('table#list').find('tr#'+rowId).show();
    } else {
    $('table#list').find('tr#'+rowId).hide();
    }
    [/code]

  10. Will it work for multiple page.

  11. I further developed the Marcin’s code: This one should work!

    // Declare variables
    var grid = $(“#list”);

    //grid complete event
    searchColumn =grid.jqGrid(‘getRowData’);
    rowid2id =grid.jqGrid(‘getCol’,'name’,true);

    //search function
    jQuery(‘#gridsearch’).keyup(function () {
    var searchString = jQuery(this).val().toLowerCase()
    for (row=0; row<searchColumn.length; row++){
    jQuery.each(searchColumn[row],function(key,value) {
    if(value.toLowerCase().indexOf(searchString) != -1) {
    jQuery('#'+rowid2id[row].id).show()
    return false;
    }else{
    jQuery('#'+rowid2id[row].id).hide()
    }
    })

    }
    });

  12. No tienes el ejemplo completo???
    o al menos el codigo de data.php

  13. Hi, thanks for the examples. I also made my version. This one allows you to select the columns you want to search.
    [Hola, gracias por los ejemplos. Yo también hice mi versíon. Esta permite seleccionar las columnas en las que se quiere buscar.]


    //Declare variables [Declara las variables]
    var grid=$("#list");
    var columns=new Array();
    //Create the grid [Crea la grilla]
    grid.jqGrid({
    datatype: "xml",
    url:"somFile.php",
    loadonce:true,
    rowNum:-1,
    colNames:['ID','Name','Description','Text'],
    colModel:[
    {name:'id',index:'id',width:50},
    {name:'name',index:'name',width:50},
    {name:'description',index:'description',width:50},
    {name:'text',index:'text',width:50}
    ],
    loadComplete:function(){
    //Empty the columns Array [Borra el Array de columnas]
    columns=new Array();
    //Add the columns to search for [Agrega las columnas en las que se quiere buscar]
    columns.push(grid.jqGrid('getCol','name',true));
    columns.push(grid.jqGrid('getCol','description',true));
    }
    });

    //Define the keyup event [Define el evento keyup]
    $("#gridsearch").keyup(function(){
    //Hide all rows and display only matching
    //[Oculta todas las filas y muestra solo las que coincidan con la búsqueda]
    grid.find(".jqgrow").hide();
    var searchString = $(this).val().toLowerCase();
    for(var i in columns){
    var column=columns[i];
    $.each(column,function(){
    var value=this.value.toLowerCase();
    if(value.indexOf(searchString) != -1){
    $('#'+this.id).show();
    }
    });
    }
    });

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">