在網上找了一些自動計算兩列的方法,全部都是只能修改已有的數據的時候自動計算,而不能在添加一行數據的時候自動計算,自己花時間研究了一下,可實現類似計算報價的功能。效果如下圖:
HTML Code:
<table id="baojia" style="width:948px;height:auto" title="報價詳細" iconCls="icon-edit" singleSelect="true" idField="itemid"> <thead> <tr> <th field="itemid" width="180" editor="text">設備名稱</th> <th field="attr1" width="80" editor="text">型號</th> <th field="brand" width="100" editor="text">品牌</th> <th field="amount" width="80" align="right" editor="{type:'numberbox',options:{precision:0}}">數量</th> <th field="listprice" width="80" align="right" editor="{type:'numberbox',options:{precision:2}}">單價</th> <th field="unitcost" width="80" align="right" editor="{type:'numberbox',options:{precision:2}}">小計</th> </tr> </thead> <tfoot> <td colspan="6">總價:</td> </tfoot> </table>
JS Code:
$(function(){ var lastIndex; $('#baojia').datagrid({ showFooter:true, fitColumns:true, toolbar:[{ text:'添加', iconCls:'icon-add', handler:function(){ $('#baojia').datagrid('endEdit', lastIndex); $('#baojia').datagrid('appendRow',{ itemid:'', attr1:'', amount:'', brand:'', unitcost:'', listprice:'' }); lastIndex = $('#baojia').datagrid('getRows').length-1; $('#baojia').datagrid('selectRow', lastIndex); $('#baojia').datagrid('beginEdit', lastIndex); setEditing(lastIndex);//此句較為重要 } },'-',{ text:'刪除', iconCls:'icon-remove', handler:function(){ var row = $('#baojia').datagrid('getSelected'); if (row){ var index = $('#baojia').datagrid('getRowIndex', row); $('#baojia').datagrid('deleteRow', index); } } }], onBeforeLoad:function(){ $(this).datagrid('rejectChanges'); }, onClickRow:function(rowIndex){ if (lastIndex != rowIndex){ $('#baojia').datagrid('endEdit', lastIndex); $('#baojia').datagrid('beginEdit', rowIndex); setEditing(rowIndex); } lastIndex = rowIndex; } }) //計算報價小計 function setEditing(rowIndex){ var editors = $('#baojia').datagrid('getEditors', rowIndex); var priceEditor = editors[4]; var amountEditor = editors[3]; var costEditor = editors[5]; priceEditor.target.bind("change", function(){ calculate(); }); amountEditor.target.bind("change", function(){ calculate(); }); function calculate(){ var cost = (priceEditor.target.val())*(amountEditor.target.val()); console.log(cost); costEditor.target.numberbox("setValue",cost); } } });
在添加按鈕的handler里加入setEditing(rowIndex);可實現在新增的行里自動計算,如果沒有加入這句,則需要再新增一行后,再回來點擊此行編輯的時候才會自動計算。