How do you handle row onclick events using Flexigrid? - javascript

My flexigrid is setup. All I need is an event that gets called when the user clicks on a row. From there, I will send the user to another page based on the data contained in that row. But I can't seem to find any examples on how to do this.
I'm looking for a clear example on how to handle row onclick events using flexigrid.
I'm also interested in any other javascript table frameworks that could be used in this situation. I've been taking a peek at DataTables and it looks like it may be a better alternative (and the project appears to be more active)

In the initial setup for the flexigrid, add the attribute process: procMe to the column model. Example:
colModel : [
{ display: 'Request', name : 'id', process: procMe }
]
and then create a callback:
function procMe( celDiv, id ) {
$( celDiv ).click( function() {
alert( id );
});
}

A better solution
Adding process to colModel didnt work for me.
colModel : [
{ display: 'Request', name : 'id', process: procMe }
]
this solution below is what I'm using:
var gridRows = $("#data-grid tbody tr");
gridRows.click(function (event) {
displaySelectedItem($(this).attr('id').substr(3));
return false; //exit
});

Flexigrid column as link
colModel: [
{
display: 'DomainName', name: 'DomainName', width: 180,
sortable: true, align: 'left',
process: function (col, id)
{
col.innerHTML = "<a href='javascript:domainEdit(" + id + ");'
id='flex_col" + id + "'>" + col.innerHTML + "</a>";
}
}]
Link Function
function domainEdit(domainID) {
alert('domainID' + domainID);
}

I think this variant little better than whoabackoff
$('.TableName').click(function(event){
$('.res').html('dbl');
alert('dbl');
});

does this help? http://www.flexigrid-asp.net/demo/updatepanel.aspx
you can have a look at it with firebug, to see where the event is hooked.
keep in mind that the flexigrid.js file is a bit different than the one from the official project.

Related

How do I fetch data from Grid in Smartclient?

How do get the underlying data from a row click on a grid?
My code looks like this :
isc.ListGrid.create({
ID: "countryList",
width:1500, height:224, alternateRecordStyles:true,
data: sampleData,
fields:[
{name:"id", title:"Id"},
{name:"name", title:"Name"},
{name:"version", title:"Version"},
{name:"release", title:"Release"},
],
canReorderFields: true,
click: function (x) {
alert('hi there' + x)
}
})
If I add a click function, the alert pops up.
If put in a paramater 'x', and that seems to have some kind of value, but i can't decipher it means. What I really want is the underlying JSON data (see below) which is being passed in as sampleData.
{
id:"10621",
name:"PimsPacket020",
version:"0.1",
release:"undefined",},
{
id:"10621",
name:"PimsPacket020",
version:"0.1",
release:"undefined",
}
I haven't been using Smartclient for quite some time, but, I think a better selection event for a grid row would be:
selectionChanged: "someFunction(this.getSelection())"
The this.getSelection() function will return an array of records even for a single selection.
For more information I suggest using the Smartclient on-line documentation( Smartclient 9.1 Documentation) and feature explorer(Smartclient Feature Explorer) together. This code work on earlier versions; from 8.x at least.
I hope this helps.
if your list contains chexbox (selectionAppearance: "checkbox") you have to use this.getSelection() that contain all selected items.
 or you make a function with record parameter:
click: function (record) {
  isc.say ("ID:" + record.id + "Name:" + record.Name);
}
Use this function to retrieve your record
recordClick: function (viewer, record, recordNum, field, fieldNum, value, rawValue) {
alert('hi there' + record.name);
}
For more information, please refer smartclient documentation
http://www.smartclient.com/docs/8.2/a/b/c/go.html#method..ListGrid.recordClick

Multiple checkbox columns in jqgrid. Handle onchange event

I am creating a jqgrid with editable fields. I have 2 checkbox columns in jqgrid, one is coming from multiselect: true (to get unique rowId), other column is created inside column model.
I want to handle the onchange(checked/unchecked) event of the checkbox in my column model, independent of other checkbox column(multiselect:true). Any help appreciated. Below is the code snippet.
[{name : "userRole", label: 'OV', width: 40, editable:true, edittype:'checkbox',formatter: 'checkbox', editoptions: {value:"True:False"},
formatoptions: { disabled: false},frozen:true}]
multiselect: true,
onSelectRow: function(rowid){
jQuery(this).editRow(rowid, true);
}
You can use beforeSelectRow callback. The demo demonstrate the approach. It uses the following code
beforeSelectRow: function (rowid, e) {
var $target = $(e.target), $td = $target.closest("td"),
iCol = $.jgrid.getCellIndex($td[0]),
colModel = $(this).jqGrid("getGridParam", "colModel");
if (iCol >= 0 && $target.is(":checkbox")) {
alert("checkbox is " +
($target.is(":checked")? "checked" : "unchecked") +
" in the column \"" + colModel[iCol].name +
"\" in the row with rowid=\"" + rowid + "\"");
}
return true;
}
Define your own formatter function like this in your colmodel,
[{name : "userRole", label: 'OV', width: 40,
editable:true, edittype:'checkbox',formatter: checkboxFormatter,
editoptions: {value:"True:False"},
And your formatted checkbox like,
function checkboxFormatter(cellvalue, options, rowObject) {
return "<input type='checkbox' name='checkboxIsCC'
onchange='your_own_function();'>";
}
Hope this helps you.
I had an issue were not only I had more than 1 check box but also I had to update same column check box values based on the selection of the check box as well as modifying the same row columns.
In regards to the modification of the other checkboxes, when jqgrid modifies the data either by 'setCell' or 'setRowData' operations, it removes the click event. Also there is the problem that for checkboxes none of the edit functions are useful.
I manage to get bits from other people's solution and came to use the delegate jquery functions, that allows the binding of the click to be done each time an object that matches the selector is created. Also in this case only 1 checkbox of only 1 column could be checked at a time.
$(document).delegate("#alarmDownloadListView td[aria-describedby*='stopArm'] input", 'click', function () {
// Function that modifies all the other checkboxes of the same column
deselectOthersStopArmAlarms(this, j);
// Set the Pre and Pos Alarm values to default
var fileIndex = $(this).closest('tr').index();
// Modification of the same row cells
if($(this).is(':checked')){
alarmsGrid.jqGrid('setCell',fileIndex,'preAlarm', defaultPrePosStopArmAlarmValue);
}else{
alarmsGrid.jqGrid('setCell',fileIndex,'preAlarm', null);
}
});
Do not mind the exact operations of the code, what is important is the operations that the binded function does. The CSS selector binds this function to all checkboxes whose name in my colmodel is stopArm.
I hope this answer is useful for some people. I found the delegate to be very useful! :)

Adding a custom button in row in jqGrid?

I want to make a simple table that contains a custom button in a row. When the button is pushed, I want to pop up an 'alert' box. I have read some posts on this, for example:
this post
and
this other post, and I don't understand why my code is not working. The buttons are drawn, but pushing them has no effect.
I have three attempts described here.
Version 1. The button click never fires:
$(document).ready(function(){
jQuery("#simpletable").jqGrid({
datatype: "local",
colNames:['A','B','Status'],
colModel:[
{name:'A',index:'A'},
{name:'B',index:'B'},
{name:'status',index:status}
],
data:[
{'A':2,'B':100,'status':"<button onclick=\"jQuery('#simpletable').saveRow('1', function(){alert('you are in')});\" >in</button>"},
{'A':1,'B':200,'status':"<button onclick=\"jQuery('#simpletable').saveRow('2', function(){alert('you are in')});\" >in</button>"},
],
caption: "Demo of Custom Clickable Button in Row",
viewrecords:true,
editurl:'clientArray',
});
});
Html Code:
<table id="simpletable"></table>
EDIT 8/2/12 -- I've learned some things since my original post and here I describe two more attempts.
Version 2: I use onCellSelect. This works, but it would not allow me to put more than one button in a cell. Additionally, I made the code nicer by using the format option suggested by one of the comments to this post.
function status_button_maker_v2(cellvalue, options, rowObject){
return "<button class=\"ver2_statusbutton\">"+cellvalue+"</button>"
};
jQuery("#simpletablev2").jqGrid({
datatype: "local",
colNames:['A','B','Status'],
colModel:[
{name:'A',index:'A'},
{name:'B',index:'B'},
{name:'status',index:status,editable:true,formatter:status_button_maker_v2}
],
data:[
{'A':2,'B':100,'status':"In"},
{'A':1,'B':200,'status':"Out"}
],
onCellSelect:function(rowid,icol,cellcontent,e){
if (icol==2){
alert('My value in column A is: '+$("#simpletablev2").getRowData(rowid)['A']);
}else{
return true;
}
},
caption: "Demo of Custom Clickable Button in Row, ver 2",
viewrecords:true,
}); //end simpletablev2
Markup:
<style>.ver2_statusbutton { color:blue;} </style>
<h3>simple table, ver 2:</h3>
<table id="simpletablev2"></table>
Version 3: I tried to use the solution to w4ik's post, using ".on" instead of deprecated ".live". This causes the button click to fire, but I don't know how to retrieve the rowid. w4ik also struggled with this, and he posted that he worked it out, but not how he did it. I can get the last row selected, but this will always refer to the previous row selected because the button is taking priority.
I would prefer this solution if I could get it to work.
jQuery("#simpletablev3").jqGrid({
datatype: "local",
colNames:['A','B','Status'],
colModel:[
{name:'A',index:'A'},
{name:'B',index:'B'},
{name:'status',index:status,editable:true,formatter:status_button_maker_v3}
],
data:[
{'A':2,'B':100,'status':"In"},
{'A':1,'B':200,'status':"Out"}
],
caption: "Demo of Custom Clickable Button in Row, ver 3",
viewrecords:true,
onSelectRow: function(){},
gridComplete: function(){}
}); //end simpletablev3
$(".ver3_statusbutton").on(
{
click: function(){
//how to get the row id? the following does not work
//var rowid = $("#simpletablev3").attr('rowid');
//
//it also does not work to get the selected row
// this is always one click behind:
//$("#simpletablev3").trigger("reloadGrid");
rowid = $("#simpletablev3").getGridParam('selrow');
alert("button pushed! rowid = "+rowid);
}
});
Markup:
<style>.ver3_statusbutton { color:red;} </style>
<h3>simple table, ver 3:</h3>
<table id="simpletablev3"></table>
In summary, I'm struggling with the issue of getting my button to be pushed at the right time. In version 1, the row gets selected and the button never gets pushed. Version 2 does not use the "button" at all -- It just handles the cell click. Verion 3 gets the button click before the row select (wrong order).
Any help would be appreciated!
You can use action formatter here with each row and make edit and delete button as false in formatOptions like this:
formatoptions: {editbutton:false,delbutton:false}}
And follow these two demos:
http://www.ok-soft-gmbh.com/jqGrid/Admin3.htm
http://ok-soft-gmbh.com/jqGrid/TestSamle/Admin1.htm
And on click event of these custom buttons show your alert:
EDIT
var getColumnIndexByName = function (grid, columnName) {
var cm = grid.jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i++) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
},
function () {
var iCol = getColumnIndexByName(grid, 'act');
$(this).find(">tbody>tr.jqgrow>td:nth-child(" + (iCol + 1) + ")")
.each(function() {
$("<div>", {
title: "Custom",
mouseover: function() {
$(this).addClass('ui-state-hover');
},
mouseout: function() {
$(this).removeClass('ui-state-hover');
},
click: function(e) {
alert("'Custom' button is clicked in the rowis="+
$(e.target).closest("tr.jqgrow").attr("id") +" !");
}
}
).css({"margin-right": "5px", float: "left", cursor: "pointer"})
.addClass("ui-pg-div ui-inline-custom")
.append('<span class="ui-icon ui-icon-document"></span>')
.prependTo($(this).children("div"));
});
}
If you check this code, I'm trying to find out index value by giving column name as 'act', you can get index on any other column by giving a different column name.
var iCol = getColumnIndexByName(grid, 'Demo'); and the rest of the code will be same for you. //demo is the column name where u want to add custom button
and write your click event for this button.
Let me know if this works for you or not.

Add Remove Column Handler on jqGrid ColumnChooser

I'm using the jqGrid columnChooser, like so:
jQuery(grid).jqGrid(
'navButtonAdd',
pagerDiv,
{
caption: "Columns",
buttonicon: "ui-icon-newwin",
title: "Hide/Show Columns",
onClickButton: function () {
$(this).jqGrid('columnChooser', {
done: function (perm) {
if (perm) {
$(this).jqGrid('remapColumns', perm, true);
}
},
modal: true,
width: 400,
height: 300,
classname: 'column-chooser-select'
});
}
}
);
and was wondering if there was a way to specify an event handler on the columnChooser (using the jQuery UI Multiselect plugin that comes w/ jqGrid) that fires any time a column is either added or removed. So I guess it's a two-part question:
does the jQuery UI Multiselect support such a thing?
if so, is there a way to hook it up without altering the jqGrid source?
A bit of background on what I'm trying to achieve:
My default grid configuration hides many columns. Some of these columns are not populated from the db - they are obscure, rarely used data elements that if populated would dramatically decrease the query execution performance (multiple joins involving tables with 100 million plus records).
Should a user pick one of these columns for display i'd like to warn them that another roundtrip to the server is required and it could take a while - and give them the option to cancel the column addition.
Thanks
I think I understand your problem and find your question interesting, so I wrote the demo for you which shows how one can solve the problem.
columnChooser uses jQuery UI Multiselect plugin internally which uses jQuery UI Sortable. So I suggest to use sortreceive event of the jQuery UI Sortable to catch the information needed.
The code can be the following
$("#grid").jqGrid('navButtonAdd', '#pager', {
caption: "",
buttonicon: "ui-icon-calculator",
title: "Choose columns",
onClickButton: function () {
$(this).jqGrid('columnChooser');
$("#colchooser_" + $.jgrid.jqID(this.id) + " ul.selected")
.bind("sortreceive", function (event, ui) {
alert('column "' + ui.item.text() + '" is choosed');
});
$("#colchooser_" + $.jgrid.jqID(this.id) + " ul.available a.action")
.click(function () {
alert('column "' + $(this).parent().text() + '" is choosed');
});
}
});
See the demo here.
The code bind 'click' event on the "+" for the initial list of the columns which was in the column chooser at the initialization time of the dialog. I think it would be sufficient for you. If needed you can easy modify the code to support the 'click' on the "+" for the columns which will be removed from the left list during the work with the columnChooser.
I almost forget to mention that I used in the demo improved version of the columnChooser (see the answer), but my above suggestion works with the original version of columnChooser too.
I am using the below code in JqGrid for column chooser plug-in. when i tick the select All check box in the grid. I want to exclude particular column ( by default it should not display in my grid).
I used hidden=True property in col model. buy i want to handle these in column chooser also.
function Properties_Columnchooser() {
$('#btn_setColumns').click(function () {
jQuery('#grid-tableProperties').jqGrid('columnChooser',{
"shrinkToFit" : true,
"autowidth" : true,
done : function(perm) {
w = $(window).width();
// alert('done ' + w);
if (perm)
{
this.jqGrid("remapColumns", perm, true);
this.setGridWidth(w - 30, true);
$('.ui-search-input').show();
}
else
{
}
}
}
);
});
}

I need sme help automating jqGrid filters, please

Okay, so in a nutshell, what I need to do is to automatically apply a set of sorting criteria and data filters to the jqGrid when it loads. The intent is that the user will start with about 10 pre-filled filters and then, if they so choose, they can alter those filters or the sorting however they see fit.
So far, with much Google-ing, trial and error and sweat, I have the following working:
-> I can load/save the sort column & sort order in a session cookie.
-> I can load the search dialog with pre-defined search filters. After the grid loads, I can open the modal dialog and see the proper filters and if I click "Find" the appropriate data is posted to the server and the right results are returned to the screen.
The thing that is biting me in the butt right now is, I think, the easy part, but it escapes me. I can't seem to do either of the following:
( A ) The ideal thing would be if I could attach these filters to the grid and it's post data in advance of the initial load so that there is only a single trip to the server.
( B ) The workable solution, though less ideal, would be for the grid to load the first page of the unfiltered data first, and then apply the filters and re-query the server for the filtered data.
Since I can manually click the "find" button today and it works, I thought that "B" would be a good next-step. So, in my gridComplete function, I have the following code:
$('#AccountGrid').clearFilter({gridName:'AccountGrid', pagerName:'AccountPager'});
$('#AccountGrid').addFilter({gridName:'AccountGrid', field:'AccountID', data:1, op:'ne'});
$('#AccountGrid').addFilter({gridName:'AccountGrid', field:'AccountID', data:3, op:'ne'});
// $('#fbox_AccountGrid').searchFilter().search();
// $('#fbox_AccountGrid .ui-search').click();
$('#AccountGrid').trigger('reloadGrid');
NOTE: "clearFilter" and "addFilter" are extension functions I have added to jqGrid to simplify adding and removing filters on the grid. They work exactly as desired at this point.
As you can see with those last three lines of code, I have tried using the built-in function, as well as going after the find button directly and even just forcing the entire grid to refresh. Either way, there is no attempt by the grid to go get new data (I am using Fiddler to watch for it).
What am I doing wrong in trying to force the grid to reload with the new filters?
And, if you know how, can you give me some direction on how to get the initial load of the grid to respect these filters?
TIA
Tony
Here is the full grid configuration (minus the extra columns and some colModel "cruft"):
jQuery('#AccountGrid').jqGrid({
url: '<my URL>',
width: 950,
height: 330,
shrinkToFit: 'true',
datatype: 'json',
mtype: 'POST',
multiselect: true,
multiboxonly: true,
multiselectWidth: 20,
colNames: [
'Account ID'
],
colModel: [
{ name: 'AccountID', index: 'AccountID', sortable: false, hidden:false, search:true }
],
gridComplete: function () {
// add the search criteria to the grid
if (initialLoad == true){
$('#AccountGrid').clearFilter({gridName:'AccountGrid', pagerName:'AccountPager'});
$('#AccountGrid').addFilter({gridName:'AccountGrid', field:'AccountID', data:1, op:'ne'});
$('#AccountGrid').addFilter({gridName:'AccountGrid', field:'AccountID', data:3, op:'ne'});
// $('#fbox_AccountGrid').searchFilter().search();
// $('#fbox_AccountGrid .ui-search').click();
$('#AccountGrid').trigger('reloadGrid');
initialLoad = false;
}
},
jsonReader: {
repeatitems: false,
id: 'AccountID'
},
pager: jQuery('#AccountPager'),
rowNum: 50,
rowList: [10, 15, 25, 50, 75, 100],
onSortCol : function (sortname, indexColumn, sortorder){
$.cookie('AccountGrid_sortname', sortname);
$.cookie('AccountGrid_sortorder' , sortorder);
},
sortname : $.cookie('AccountGrid_sortname') ? $.cookie('AccountGrid_sortname') : 'AccountID',
sortorder: $.cookie('AccountGrid_sortorder') ? $.cookie('AccountGrid_sortorder') : 'asc',
viewrecords: true,
imgpath: ''
});
$('#AccountGrid').jqGrid('navGrid','#AccountPager',
{ view: false, add: false, edit: true, del: false,
alertcap:'No Account Selected',
alerttext: 'Please select an Account from the grid before performing this operation.',
editfunc: showAccountEditDialog },
{}, // default settings for edit
{}, // default settings for add
{}, // delete
{closeOnEscape: true, multipleSearch: true, closeAfterSearch: true }, // search options
{}
);
And, by request, here is the code I have for add/clear filter:
/*
This is a grid extension function that will insert a new filter criteria
on the specified grid with the provided field, operation & data values
*/
(function ($) {
jQuery.jgrid.addSearchFilter =
{
// get/set the parameters
addFilter: function (options) {
var grid = $(this);
// get offset values or assign defaults
var settings = $.extend({
gridName: '',
field: '',
data: '',
op: ''
}, options || {});
// get the column model object from the grid that matches the provided name
var colModel = grid.getGridParam('colModel');
var column;
for (var i = 0; i < colModel.length; i++) {
if (colModel[i].name == options.field){
column = colModel[i];
break;
}
}
colModel = null;
if (column){
// if the last filter has a value, we need to create a new one and not overwrite the existing ones
if ($('#fbox_' + options.gridName + ' .sf .data input').last().val()){
$('#fbox_' + options.gridName).searchFilter().add();
}
// assign the selections to the search dialog
$('#fbox_' + options.gridName + ' .sf .fields select.field').last().val(column.index).change();
$('#fbox_' + options.gridName + ' .sf .data input').last().val(options.data);
$('#fbox_' + options.gridName + ' .sf .ops select.default').last().val(options.op).change();
}
}
}
})(jQuery);
jQuery.fn.extend({ addFilter: jQuery.jgrid.addSearchFilter.addFilter });
/*
This is a grid extension function that will clear & reset the filter criteria
*/
(function ($) {
jQuery.jgrid.clearSearchFilter =
{
// get/set the parameters
clearFilter: function (options) {
var grid = $(this);
// get offset values or assign defaults
var settings = $.extend({
gridName: '',
pagerName: ''
}, options || {});
// clear the filters and "pop" the dialog to force the HTML rendering
$('#fbox_' + options.gridName).searchFilter().reset();
$('#' + options.pagerName + ' .ui-icon-search').click();
$('#fbox_' + options.gridName).searchFilter().close();
}
}
})(jQuery);
jQuery.fn.extend({ clearFilter: jQuery.jgrid.clearSearchFilter.clearFilter });
First of all because you don't post the code which define the jqGrid I make some assumption myself. I try to base on indirect information from your question.
1) I suppose that you use server side datatype parameter of jqGrid like 'json' or 'xml'.
2) You don't use loadonce:true parameter. In general if would be possible to make server reload from the grid having loadonce:true, but in the case you have to reset the value of datatype parameter to initial value (one from the value 'json' or 'xml').
The following three old answer: this (in case of single value searching) and this (in case of advanced searching or the toolbar searching with additional parameter stringResult:true) will give you enough information about setting the searching filters and reloading the grid corresponds to the new filters. Another answer shows how to clear the searching filter if it is no more needed.
Loading of the grid at the first time with the filters is another question. It can be very easy implemented. You should just use datatype:"local" instead of datatype:"json" or datatype:"xml" which you really need. In the case the url parameter of jqGrid will be just ignored at the first load and jqGrid send no request to the server. Then you set the filters like you as need and only then use $("#youGridId").trigger("reloadGrid");
The reason why the reloadGrid didn't work in your case I could not know exactly, but I suppose that you didn't set the search:true parameter of the jqGrid which one confuses frequently with the _search property of the postData parameter (see here).

Categories

Resources