Skip to content

Javascript API FAQs

Javascript API FAQs

Q) How can i get IDs or Data of the selected rows of grid?

On client side, you can have ids in this way, where "list1" is grid identifier.

Returns null if no row is selected (single row)

var selr = jQuery('#list1').jqGrid('getGridParam','selrow');

Return array of id's of the selected rows when multiselect options is true. Empty array if not selection

var selr = jQuery('#list1').jqGrid('getGridParam','selarrrow');

Return data of passed row and col, where invdate is column name

var rd = jQuery('#list1').jqGrid('getCell', selr, 'invdate');

To get all ids

var rows = $('#list1').jqGrid('getDataIDs');

Get particular column data, returns array

var data = $('#list1').jqGrid('getCol', 'total');

Get particular column properties, returns array

var prop = $('#list1').jqGrid('getColProp', 'total');
alert(prop.editrules.required);

Set particular column properties

$('#list1').jqGrid('setColProp', 'total', {editrules: {required:true} });

To select / unselect grid row, e.g. rowid 5

jQuery('#list1').jqGrid('setSelection', 5, true);

To reset grid selections

jQuery('#list1').jqGrid('resetSelection');

To hide/show grid columns (e.g.invdate)

jQuery('#list1').jqGrid('hideCol','invdate');
jQuery('#list1').jqGrid('showCol','invdate');

To select all grid rows

jQuery('#list1').jqGrid('resetSelection');
var ids = jQuery('#list1').jqGrid('getDataIDs');
for (i = 0; i < ids.length; i++) {
    jQuery('#list1').jqGrid('setSelection', ids[i], true);
}

You get all row data for rowid '3'

var row =  $('#list1').getRowData(3);

// Sample row data output is:
{invid:"1", invdate:"2007-10-01", note:"note", amount:"200.00", tax:"10.00", total:"210.00"};

To get all data in 2d array, call getRowData without param.

var rows =  $('#list1').getRowData();

To get current search filter

// will give you a string like: "{"groupOp":"AND","rules":[{"field":"Name","op":"bw","data":"a"}]}"
var filters = $('#list1').getGridParam("postData").filters;

To get all column titles

// returns array with col titles ["Client Id", "Name", "Gender", "Company", "Actions"]
var colNames = jQuery("#list1").jqGrid("getGridParam", "colNames");

To get all column details

// returns array with complete column object, use firebug console.log(colModel); for details.
var colModel = jQuery("#list1").jqGrid("getGridParam", "colModel");

^ Top

Q) How to bind Javascript events with controls e.g. textbox?

You can set them using editoptions

$col = array();
$col["title"] = "Name"; // caption of column
...
$col["editoptions"] = array("onkeyup"=>"this.value=this.value.toUpperCase()");
$cols[] = $col;

^ Top

Q) How to reload/refresh grid using javascript code (e.g. button click)?

You can call this JS code to reload grid. (where 'list1' is grid identifier)

jQuery('#list1').trigger("reloadGrid",[{page:1}]);

To preserve page number on refresh, you "current" config.

$("#list1").trigger("reloadGrid", [{current:true}]);

If you wish to auto reload grid at e.g. 2 min interval, you can call this JS code.

setInterval("jQuery('#list1').trigger('reloadGrid',[{page:1}]);",2000);

^ Top

Q) How to call custom javascript function on Add/Edit/Del button click?

For instance, if you need custom edit button, You can remove default edit button by following config.

$g->set_actions(array(
                        "add"=>false, // allow/disallow add
                        "edit"=>false, // allow/disallow edit
                        "delete"=>true, // allow/disallow delete
                        "rowactions"=>true, // show/hide row wise edit/del/save option
                        "export"=>true, // show/hide export to excel option
                        "autofilter" => true, // show/hide autofilter for search
                        "search" => "advance" // show single/multi field search condition (e.g. simple or advance)
                    )
                );

And add your custom button using this JS (where list1 is grid id). You can also reference grid id with $g->id (where $g = new jqgrid();). This also works with subgrid.

<script type="text/javascript">
/*
    CUSTOM TOOLBAR BUTTON
    ---------------------
    caption: (string) the caption of the button, can be a empty string.
    buttonicon: (string) is the ui icon name from UI theme icon set. If this option is set to 'none' only the text appear.
    onClickButton: (function) action to be performed when a button is clicked. Default null.
    position: ('first' or 'last') the position where the button will be added (i.e., before or after the standard buttons).
    title: (string) a tooltip for the button.
    cursor : string (default pointer) determines the cursor when we mouseover the element
    id : string (optional) - if set defines the id of the button (actually the id of TD element) for future manipulation
*/
jQuery(document).ready(function(){
    jQuery('#list1').jqGrid('navButtonAdd', '#list1_pager',
    {
        'caption'      : '',
        'buttonicon'   : 'ui-icon-pencil',
        'onClickButton': function()
        {
            // your custom JS code ...
            redireciona();
            function redireciona() {window.location="cadastrar.php";}
        },
        'position': 'first'
    });
});
</script>

^ Top

Q) How to post data using JS code?

Assuming, you are posting to grid with id (list1), here is the sample JS code. "id" is PK (_empty), "oper" will be "add" for new record. Rest are the table fields in myData.

<script>
    auto_add = function ()
    {
        myData = {};
        myData.id = "_empty";
        myData.oper = 'add';
        myData.invdate = '2013-06-12';
        myData.note = 'test2';
        myData.total = '22';
        myData.client_id = '10';
        jQuery.ajax({
            url: "?grid_id=list1",
            dataType: "json",
            data: myData,
            type: "POST",
            error: function(res, status) {
                alert(res.status+" : "+res.statusText+". Status: "+status);
            },
            success: function( data ) {
            }
        });
        jQuery("#list1").jqGrid().trigger('reloadGrid',[{page:1}]);
    }
</script>

<button onclick="auto_add()">Add</button>

^ Top

Q) How to we set grid caption using javascript code?

You can use setCaption method to set new caption on the grid:

var grid = $('#myjqgrid');
grid.jqGrid('setCaption', 'newCaption');

^ Top

Q) How to remove sorting & filters on reload?

Step1: Remove default refresh button from toolbar.

$g->set_actions(array(
                        // ...
                        "refresh"=>false, // show/hide export to excel option
                        // ...
                    )
                )

Step2: Add custom toolbar button using javascript, with refresh data code.

jQuery(document).ready(function(){

    jQuery('#list1').jqGrid('navButtonAdd', '#list1_pager',
    {
        'caption'      : 'Reload',
        'buttonicon'   : 'ui-icon-refresh',
        'onClickButton': function()
        {
            var myGrid = jQuery("#list1");
            jQuery("span.s-ico",myGrid[0].grid.hDiv).hide(); // hide sort icons

            // reset filters and sort field
            myGrid.setGridParam({
                        postData: { filters: JSON.stringify({groupOp: "AND", rules:[]}) }, sortname: ''
                    }).trigger('reloadGrid');

            // empty toolbar fields
            jQuery(".ui-search-input input").val("");

        },
        'position': 'last'
    });
});

OR, if we want to persist search filter on refresh

jQuery(document).ready(function(){
    jQuery('#list1').jqGrid('navButtonAdd', '#list1_pager',
    {
        'caption'      : '',
        'buttonicon'   : 'ui-icon-refresh',
        'onClickButton': function()
        {
            var myGrid = jQuery("#list1");
            var filters = myGrid.getGridParam("postData").filters;
            // reset filters and sort field
            myGrid.setGridParam({
                        postData: { 'filters': filters }, sortname: ''
                    }).trigger('reloadGrid');
        },
        'position': 'last'
    });
});

^ Top