Setting data attribute on each row of a jqgrid table - jqgrid

I am using jqGrid and I'm trying to add a data- attribute to each tr. I'm firing the loadComplete event, but I'm unsure of how to modify each row. Any code samples?

You can use rowattr to assign any additional attribute to <tr> elements (see the answer and this one for code examples). For example you can use
rowattr: function (rd) {
return {"data-mydata": JSON.stringify(rd)};
}
to save full input row data as data-mydata attribute. I recommend you to use rowattr``in combination withgridview: true` option to have the best performance results ()
The demo uses above rowattr cade and you can see that rows of grid have additional data-mydata attribute:

In my cases, I set the first column of grid by an identity. And in all my cases, id of each data row of my grids is the value of that identity column.
jqGrid column:
colModel: [
{
name:'ID',
label:'...',
width:1,
index:'ID'
...
Rendered :
<tr role="row" id="10777" ... > // in retrieved data: ID = 10777
So, if you have similar declarations like me, this could be a useful selector for you and you can simply add your data- attrib to these rows like this:
$('#trId').prop('data-whatever', 'value');
And if you want the above line to be performed automatically to all rows, you should change it slightly and put it into the gridComplete event of your grid:
gridComplete: function() { $("tr[role='row']").prop('data-whatever', 'value'); }

Related

jqGrid Autocomplete Inline Editing

I have a grid using jqGrid and in this grid I have the rows editable with inline editing. I'm trying to do autocomplete in the rows that is editable. Is this possible to do? And in case of yes, how can I identify these rows?
You could set the classes: autoCompleteFieldClassName in the colModel of the column, and then use that to add in your auto complete fields on edit.
Example:
in the colModel you can assign a class to the column cells via the option
classes: autoCompleteFieldClassName
This class would then allow you to set a jQuery selector on the inline edit event which would allow you to select the input element attached to this cell column. Once you have this element you can attach an jQuery autocomplete
$(inputElement).autocomplete({ source: '/Controller/GetAutocompleteInformation',
minLength: 2, autosearch: true,
select: function (event, ui) {
$(elem).val(ui.item.value);

while the select editoption posts the value (or id) of the selected list item, autocomplete posts the label - i need id posted

While both autocomplete and select in jqgrid editform place the selected label into the cell, select will place the value (id) in the postdata array where autocomplete will place the label into the postdata array.
is there a way to get the editoption's autocomplete to post the item value (id) instead of the label?
here is the jqgrid code segment i'm using autocomplete in...
$('#tab3-grid').jqGrid({
colNames:['Workorder', 'wo.CUID',.....],
colModel:[
.
.
.
{name:'wo.CUID', index:'cu.LastName', width:120, fixed:true, align:'center', sortable:true, editable:true, edittype:'text',
editoptions:{dataInit:function(el){$(el).autocomplete({ source: 'php/customer-ac-script.php'
, minLength: 1
})
}
},
formoptions:{rowpos: 1, label:'Customer', elmprefix:'* '},
editrules:{required:true}
},
.
.
.
$('#tab3-grid').jqGrid('navGrid', '#tab3-pager',
{view:true, closeOnEscape:true, cloneToTop:true}, // general parameters that apply to all navigation options below.
{jqModal:true, navkeys:[true,38,40], savekey:[true,13]}, // edit options.
{jqModal:true, navkeys:[true,38,40], savekey:[true,13], reloadAfterSubmit:false, afterSubmit: addRecordID}, // add options.
{jqModal:true, afterSubmit: serverMessage}, // del options.
{jqModal:true}, // search options.
{jqModal:true, navkeys:[true,38,40]} // view options.
);
The php code segment:
// construct autocomplete select.
$i = 0;
while($row = mysql_fetch_assoc($result)) {
$output[$i][$crudConfig['id']] = $row['CUID'];
$output[$i][$crudConfig['value']] = $row['LastName'];
logMsg(__LINE__,'I','cu.CUID: '.$row['CUID'].', cu.LastName: '.$row['LastName']);
$i++;
}
// encode to json format and send output back to jqGrid table.
echo json_encode($output);
logMsg(__LINE__,'I','Send json output back to jqGrid table: '.json_encode($output));
Would it be as simple as calling a function under the autocomplete select event or the grid before or after editform submit?
Also, i noticed this note in the jqgrid doc's for datainit: that says...
Note: Some plugins require the position of the element in the DOM and
since this event is raised before inserting the element into the DOM
you can use a setTimeout function to accomplish the desired action.
Would the lack of including the settimeout function be causing the problem?
The server code which provide the JSON response on the autocomplete request has id and value properties. On the other side the standard behavior of jQuery UI Autocomplete is to use label and value properties (see "Datamodel" in the documentation). The value of label property (if any exist) will be used to display in the contextmenu. The value of value property will be placed in the <input> field after the user choose the item from the contextmenu. The value of label property can has HTML markup, but the value of value property must be the text.
So I see the problem as pure problem of the usage of jQuery UI Autocomplete independent on jqGrid. If I understand correct your question you can solve your problem by modification your server side code.
Oleg's answer clarifying the data model for jquery UI's autocomplete, has allowed me to move forward and understand that autocomplete has nothing to do with constructing and sending the postdata array to the server, jqgrid's editform handles it. With that knowledge, i was able to answer my original question and successfully integrate autocomplete into jqgrid. So, in the interest of sharing, i'd like to show you all my motivation and solution.
By default, selecting a label from the autocomplete list put's the value of the selected label/value pair into the text box. All the editform cares about when you submit is what's in the edit fields. So when you submit the editform, the cell's postdata element value will again contain the value of the autocomplete text box. But what if while wanting to post the value of the label/value pair, you want the label of the label/value pair displayed in the text box? You have a problem! How do you get the value of the label/value pair posted to the server?
Well, after spending a few days on it, it turns out to be quite simply. While i'm sure there is more than one solution, here is mine:
add a hidden id column in the grid
define the select: and focus: events in the autocomplete function
in the select: function; insert the selected label into the text box (optional), disable the default behavior of autocomplete, then set the cell of the hidden column to the value of the selected label/value pair
in the focus: function; insert the selected label into the text box(optional), disable the default behavior of autocomplete
add an "onclickSubmit:" event to the navgrid edit options with function name something like "fixpostdata"
in the "fixpostdata" function; get the cell value of the hidden column and insert it into the postdata element associated with the cell.
The following are the grid and javascript code segments i used…
grid segments
{name:'wo_CUID', index:'wo_CUID', width: 70, hidden: true},
{name:'wo.CUID', index:'cu.LastName', width:120, sortable:true, editable:true, edittype:'text',
editoptions:{
dataInit:function(el){ // el contains the id of the edit form input text box.
$(el).autocomplete({
source: 'php/customer-ac-script.php',
minLength: 1,
select: function(event, ui){event.preventDefault();
$(el).val(ui.item.label);
var rowid = $('#tab3-grid').getGridParam('selrow');
// set the hidden wo_CUID cell with selected value of the selected label.
$('#tab3-grid').jqGrid('setCell', rowid,'wo_CUID',ui.item.value);},
focus: function(event, ui) {event.preventDefault();
$(el).val(ui.item.label);}
})
}
},
formoptions:{rowpos: 1, label:'Customer', elmprefix:'* '},
editrules:{required:true}
},
.
.
$('#tab3-grid').jqGrid('navGrid', '#tab3-pager',
{view:true, closeOnEscape:true, cloneToTop:true},
{jqModal:true, navkeys:[false,38,40], onclickSubmit: fixpostdata}, // edit options.
.
.
javascript function
// define handler function for 'onclickSubmit' event.
var fixpostdata = function(params, postdata){
var rowid = $('#tab3-grid').getGridParam('selrow');
var value = $('#tab3-grid').jqGrid('getCell', rowid,'wo_CUID');
postdata['wo.CUID'] = value;
return;
}
The fixpostdata function fires when you submit the editform but befor the postdata array is sent to the server. At this point you replace the cell's postdata element value with whatever you want. In this case, the value of the label/value pair stored in the hidden column cell. When the function returns, the modified postdata array is sent to the server.
Done!

How to set default field values for add form in jqgrid from current row

Add toolbar button is used to add new row to jqgrid.
Add form which appears contains all filed vlaues empty.
How to set add form field values from column values from row which was current/selected when add command was issued ?
json remote data is used. Or if this is simpler, how to call server method passing current/selected row to retrieve default values for add form from server ?
jqgrid contains also hidden columns. If possible values from hidden columns from current row should also sent to add controller if add form is saved.
Update
I tried to use Oleg great suggestion by using
afterShowForm: function(formID) {
var selRowData,
rowid = grid.jqGrid('getGridParam', 'selrow');
if (rowid === null) {
// todo: how to cancel add command here
alert('Please select row');
return;
}
selRowData = grid.jqGrid('getRowData', rowid);
if (selRowData === null) {
alert('something unexpected happened');
return;
}
$('#' + 'Baas' + '.FormElement', formID).val(selRowData.Baas);
}
Application keeps add form open after saving. After first save Baas field is empty. It looks like afterShowForm event runs only once, not after every save. How to fix this so that multiple rows with default values can added without closing add form?
How to cancel or not allow Add command if there is no selected row ?
If you need to make some initialization actions only for Add form you can use at least two approaches:
the usage of defaultValue property as function inside of editoptions. The callback function defaultValue can provide the value for the corresponding field of the Add form based of the data from selected row. For optimization purpose you can read the data from the current selected row once in the beforeInitData callback/event. You can just read the data which you need or make an synchronous call to the server to get the information which you need. The only disadvantage of the usage of defaultValue property is that it uses jQuery.val method to set the default value for all fields of Add form with exception 'checkbox' edittype. For the checkboxs jqGrid set checked property of the checkbox of false, 0, no, off or undefined are not found in the value returned by defaultValue property. So the approach will not work for other edittypes. For example it can fail for the custom edittype.
the usage of beforeShowForm or afterShowForm. Inside of the callback functions you can set any value of the form. You can find the filed of the corresponding column of the grid by id of the field which is the same as the value of name property of the corresponding column.
Like you already knows you can get the id of the current selected row with respect of getGridParam and get the data from the selected row
var selRowData, rowid = grid.jqGrid('getGridParam', 'selrow');
if (rowid !== null) {
// a row of grid is selected and we can get the data from the row
// which includes the data from all visible and hidden columns
selRowData= grid.jqGrid('getGridParam', 'selrow');
}
where grid is jQuery object like $('#list') which selects the main <table> element of the grid.
In the demo you can see how works the first approach described above.

Browser Memory Usage Comparison: inline onClick vs. using JQuery .bind()

I have ~400 elements on a page that have click events tied to them (4 different types of buttons with 100 instances of each, each type's click events performing the same function but with different parameters).
I need to minimize any impacts on performance that this may have. What kind of performance hit am I taking (memory etc) by binding click events to each of these individually (using JQuery's bind())? Would it be more efficient to have an inline onclick calling the function on each button instead?
Edit for clarification :):
I actually have a table (generated using JQGrid) and each row has data columns followed by 4 icon 'button' columns- delete & three other business functions that make AJAX calls back to the server:
|id|description|__more data_|_X__|_+__|____|____|
-------------------------------------------------
| 1|___data____|____data____|icon|icon|icon|icon|
| 2|___data____|____data____|icon|icon|icon|icon|
| 3|___data____|____data____|icon|icon|icon|icon|
| 4|___data____|____data____|icon|icon|icon|icon|
I am using JQGrid's custom formatter (http://www.trirand.com/jqgridwsiki/doku.php?id=wiki:custom_formatter) to build the icon 'buttons' in each row (I cannot retrieve button HTML from server).
It is here in my custom formatter function that I can easily just build the icon HTML and code in an inline onclick calling the appropriate functions with the appropriate parameters (data from other columns in that row). I use the data in the row columns as parameters for my functions.
function removeFormatter(cellvalue, options, rowObject) {
return "<img src='img/favoritesAdd.gif' onclick='remove(\"" + options.rowId + "\")' title='Remove' style='cursor:pointer' />";
}
So, I can think of two options:
1) inline onclick as I explained above
--or--
2) delegate() (as mentioned in below answers (thank you so much!))
Build the icon image (each icon type has its own class name) using the custom formatter.Set the icon's data() to its parameters in the afterInsertRow JQGrid event. Apply the delegate() handler to buttons of specific classes (as #KenRedler said below)
> $('#container').delegate('.your_buttons','click',function(e){
> e.preventDefault();
> var your_param = $(this).data('something'); // store your params in data, perhaps
> do_something_with( your_param );
> }); //(code snippet via #KenRedler)
I'm not sure how browser-intensive option #2 is I guess...but I do like keeping the Javascript away from my DOM elements :)
Because you need not only a general solution with some container objects, but the solution for jqGrid I can suggest you one more way.
The problem is that jqGrid make already some onClick bindings. So you will not spend more resources if you just use existing in jqGrid event handler. Two event handler can be useful for you: onCellSelect and beforeSelectRow. To have mostly close behavior to what you currently have I suggest you to use beforeSelectRow event. It's advantage is that if the user will click on one from your custom buttons the row selection can stay unchanged. With the onCellSelect the row will be first selected and then the onCellSelect event handler called.
You can define the columns with buttons like following
{ name: 'add', width: 18, sortable: false, search: false,
formatter:function(){
return "<span class='ui-icon ui-icon-plus'></span>"
}}
In the code above I do use custom formatter of jqGrid, but without any event binding. The code of
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol >= firstButtonColumnIndex) {
alert("rowid="+rowid+"\nButton name: "+buttonNames[iCol]);
}
// prevent row selection if one click on the button
return (iCol >= firstButtonColumnIndex)? false: true;
}
where firstButtonColumnIndex = 8 and buttonNames = {8:'Add',9:'Edit',10:'Remove',11:'Details'}. In your code you can replace the alert to the corresponding function call.
If you want select the row always on the button click you can simplify the code till the following
onCellSelect: function (rowid,iCol/*,cellcontent,e*/) {
if (iCol >= firstButtonColumnIndex) {
alert("rowid="+rowid+"\nButton name: "+buttonNames[iCol]);
}
}
In the way you use one existing click event handler bound to the whole table (see the source code) and just say jqGrid which handle you want to use.
I recommend you additionally always use gridview:true which speed up the building of jqGrid, but which can not be used if you use afterInsertRow function which you considered to use as an option.
You can see the demo here.
UPDATED: One more option which you have is to use formatter:'actions' see the demo prepared for the answer. If you look at the code of the 'actions' formatter is work mostly like your current code if you look at it from the event binding side.
UPDATED 2: The updated version of the code you can see here.
You should use the .delegate() method to bind a single click handler for all elements ,through jQuery, to a parent element of all buttons.
For the different parameters you could use data- attributes to each element, and retrieve them with the .data() method.
Have you considered using delegate()? You'd have one handler on a container element rather than hundreds. Something like this:
$('#container').delegate('.your_buttons','click',function(e){
e.preventDefault();
var your_param = $(this).data('something'); // store your params in data, perhaps
do_something_with( your_param );
});
Assuming a general layout like this:
<div id="container">
<!--- stuff here --->
<a class="your_buttons" href="#" data-something="foo">Alpha</a>
<a class="your_buttons" href="#" data-something="bar">Beta</a>
<a class="your_buttons" href="#" data-something="baz">Gamma</a>
<a class="something-else" href="#" data-something="baz">Omega</a>
<!--- hundreds more --->
</div>

How to capture jqGrid column changing events?

In our application we are using a jqGrid which supports hiding and reordering of columns. When the columns are hidden or reordered we want to store the new settings into our database. But to do this we somehow need to capture the hiding or reordering event. Or possibly to capture when the colModel changes.
Is there any way to capture and handle these events?
Thanks.
You can use 'done' event of the columnChooser. Here is an example:
var grid = $("list");
grid.navButtonAdd(
'#pager',
{caption:"", buttonicon:"ui-icon-calculator", title:"Column choose",
onClickButton: function() {
grid.jqGrid('columnChooser',
{
"done": function(perm) {
if (perm) {
this.jqGrid("remapColumns", perm, true);
}
// here you can do some additional actions
}
});
}
});
UPDATED: If you define sortable option as
sortable: {
update: function (permutation) {
alert("sortable.update");
}
}
and not as sortable:true you will receive the notification about the new order of columns. See the source code of jqGrid for details. The array permutation with integers has the same meaning as in remapColumns functions (see my old answer for details).
You can capture column changes via the sortable parameter as mentinoed in Oleg's "update" above, or as discussed on jqGrid's message board.
However, please note that the array passed to your callback will be relative to the current column order. In other words, saving the array as is after moving multiple columns will not produce the desired results. See my answer on this other stackoverflow question.

Resources