jQuery EasyUI DataGrid - Calculated Column
In this tutorial, you will learn how to include a calculated column in an editable datagrid. A calculated column typically contains values derived from one or more other columns.
First, create an editable datagrid. Here, we have created some editable columns, with 'listprice', 'amount', and 'unitcost' columns defined as numberbox editor types. The calculated column is the 'unitcost' field, which will be the result of multiplying the 'listprice' by the 'amount' column.
<table id="tt" style="width:600px;height:auto"
title="Editable DataGrid with Calculated Column" iconCls="icon-edit" singleSelect="true"
idField="itemid" url="data/datagrid_data.json">
<thead>
<tr>
<th field="itemid" width="80">Item ID</th>
<th field="listprice" width="80" align="right" editor="{type:'numberbox',options:{precision:1}}">List Price</th>
<th field="amount" width="80" align="right" editor="{type:'numberbox',options:{precision:0}}">Amount</th>
<th field="unitcost" width="80" align="right" editor="numberbox">Unit Cost</th>
<th field="attr1" width="150" editor="text">Attribute</th>
<th field="status" width="60" align="center" editor="{type:'checkbox',options:{on:'P',off:''}}">Status</th>
</tr>
</thead>
</table>
When a user clicks on a row, we initiate an edit action.
var lastIndex;
$('#tt').datagrid({
onClickRow:function(rowIndex){
if (lastIndex != rowIndex){
$('#tt').datagrid('endEdit', lastIndex);
$('#tt').datagrid('beginEdit', rowIndex);
setEditing(rowIndex);
}
lastIndex = rowIndex;
}
});
To create a calculation relationship between some columns, we should get the current editors and bind some events to them.
function setEditing(rowIndex){
var editors = $('#tt').datagrid('getEditors', rowIndex);
var priceEditor = editors[0];
var amountEditor = editors[1];
var costEditor = editors[2];
priceEditor.target.bind('change', function(){
calculate();
});
amountEditor.target.bind('change', function(){
calculate();
});
function calculate(){
var cost = priceEditor.target.val() * amountEditor.target.val();
$(costEditor.target).numberbox('setValue',cost);
}
}