The Routines Called by the Grids

Define some variables used in calculating the amount needed to balance the transaction. We do these calculations on every change so that we can keep the operator always aware of the state of the transaction. And, this application sometimes involves foreign exchange.

var CurrencyFK = 5; var Conversion = 1.000; var SeriesSign = -1; var TransSign = 0; var Balance = 0 ; // Balance is converted to a common currency as required; Raw is the amount before conversion var Raw = 0 ; var ThisTrans = '' ; var TransChanged = false; var cntdtl = 1;

Define the urls we are going to need (makes for shorter code elsewhere and easier to maintain)
// Get, Put and Delete records in the Master Grid // Putting does nothing, but could be used to retrieve some identifying data from the server, if necessary // Deleting a Master record also deletes the Details, on the server if the transaction has been previously saved var masterurl = 'some url'; var masterediturl = 'some url'; var masterdelete = 'some url'; // Get, Put and Delete records in the Details Grid // Putting does nothing // Deleting a Details record (if it has been previously saved) deletes it on the server var detailurl = 'some url'; var detailediturl = 'some url'; var detaildelete = 'some url'; // Saving a transaction happens only with a Post var posturl = 'some url'; // Several fields use autocomplete, another jQuery plugin var searchaccount = 'some url'; var searchcv = 'some url' ; var searchproject = 'some url' ; var searchinvoice = 'some url' ;

The following variables are the add, edit and delete parameters referred to in the definition of the grids. They provide both settings (e.g., height and width) and functions that apply when the edit forms are active. The add and edit parameters are essentially the same for each grid. If it weren't for some minor (but important differences) we could use a single variable with combined logic for both functions.

First the Master grid:

// adding Master records var addmasterprm = { width: 500, height: 300, top: 125, left: 50, reloadAfterSubmit:false, closeAfterAdd:true, addCaption : "Add Bank Side", onInitializeForm : function (formid){ // cvname autocomplete; data is returned as cvname|cvfk $("#cvname",formid).autocomplete(searchcv,{ mustMatch: true }); $("#cvname",formid).result(function(event, data, formatted) { if (data) { $("#cvfk",formid).val(data[1]); } }); // datepicker $("#issued",formid).datepicker({showOn:'button', buttonImage: '../images/Calendar.jpg', buttonImageOnly: true, constrainInput: true }); }, beforeShowForm : function (formid) { // if we had settings to reconfigure every time we add new record, we would do it here }, afterSubmit: function(data,postdata) { // postdata is what we post to server // nothing is returned from server ThisTrans = "X"; TransChanged = true; $("#tblDetails") .setCaption("Details: New Transaction") .setGridParam({datatype:'local'}); // we are ready to enter details, reset the counter cntdtl =1; return [true,"",ThisTrans]; }, afterComplete : function (data,postdata){ GoToDetails(ThisTrans); setTimeout(function(){$("#tblDetails").editGridRow("new",adddtprm)},200); } }; // editing Master records var editmasterprm = { width: 500, height: 300, top: 125, left: 50, reloadAfterSubmit:false, closeAfterEdit:true, editCaption : "Edit Bank Side", onInitializeForm : function (formid){ // cvname autocomplete // data is returned this way as cvname|cvfk $("#cvname",formid).autocomplete(searchcv,{ mustMatch: true }); $("#cvname",formid).result(function(event, data, formatted) { if (data) { $("#cvfk",formid).val(data[1]); } }); // datepicker $("#issued",formid).datepicker({showOn:'button'}); }, beforeShowForm : function(formid) { // Hide the Next and Previous buttons $("#pData,#nData",formid).hide(); }, afterSubmit : function(data,postdata) { // compare the posted data with the grid data // if there is a change set TransChanged to true var masterrec = $("#tblMaster").getRowData(postdata.id); // we do reverse comparing the base is the grid data not postdata $.each(masterrec,function(name,value) { if(postdata[name] !== value) { TransChanged = true; return false; } }); CalcNet(ThisTrans,postdata); return [true,""]; } }; // deleting Master records var delmasterprm = { url:masterdelete, reloadAfterSubmit: false, afterSubmit : function(data,postdata){ // Check the response from server (data) // Add your own condition analyzing the data response if(1==1 ){ // clear the details grid $("#tblDetails") .clearGridData() .setCaption("Select an Item, above, to view or edit details here"); // clear the messages $("#tblDetailsMessage").html(""); // hide the button $("#fullpage_cmdsavetrans").hide(); $("#fullpage_cmdcancel").hide(); // initial transaction set ThisTrans = 0; TransChanged = false; return [true]; } else { return [false]; } } };

Now the Details grid, where much more happens for each record, so these are very different from the parameters for the Master grid. But again, with a little code tweaking, the add and edit parameters could be combined to save space on download time.
// Adding Details records var adddtprm = { width: 500, height: 350, top: 125, left: 50, reloadAfterSubmit:false, closeAfterAdd:false, addedrow : "last", addCaption : "Add Distribution Side", onInitializeForm : function (formid){ $("#invoice",formid).keypress(function(e) {; var keynum ; if(window.event) { // IE keynum = e.keyCode; } else { // Netscape/Firefox/Opera keynum = e.which; }; if (keynum == 13) { var ret = CheckInvoice(formid) } } ) ; $("#invoice",formid).change(function() {; var ret = CheckInvoice(formid) } ) ; // These fields are always disabled $("#invoiced",formid).attr('disabled',true); $("#outstanding",formid).attr('disabled',true); $("#project",formid).after('<span id="prbut"><img src="../images/find.gif" border="0" alt="Find Project"/></span>'); $("#prbut",formid).click(function(){ modal_win('',"Search Projects",{top:60,height:450,width:780,left:50}); $.ajax({ url: "some url", dataType:"html", error: function (req,sttext) { alert(sttext+" : " +req) }, success: function(req) { $("#doc_content","#doc_dialog").html(req); $("#sg_client", "#search_form").autocomplete(searchcv ); $("#tblprojects").setGridParam({ onSelectRow : function (rowid) { var srarray = $("#tblprojects").getRowData(rowid); $("#projectfk",formid).val(srarray.projectpk); $("#project",formid).val(srarray.projectname); $("#projectnumber",formid).val(srarray.projectbumber); $("#shorttitle",formid).val(srarray.shorttitle); $("#structurefk",formid).val(srarray.structurefk); $("#client",formid).val(srarray.client); $("#clientfk",formid).val(srarray.clientfk); if (srarray.structurefk === "37") { alert('Multi-client Project; please select client' ) ; $("#tr_client",formid).show(); } $("#doc_dialog").jqmHide(); } }); } }); }); // Projects autocomplete $("#tr_projectnumber",formid).hide(); $("#tr_shorttitle",formid).hide(); if ($("#structurefk",formid).val !== "37") { $("#tr_client",formid).hide(); }; $("#project",formid).autocomplete(searchproject,{ mustMatch: true }); $("#project",formid).result(function(event, data, formatted) { if (data) { $("#projectnumber",formid).val(data[1]); $("#shorttitle",formid).val(data[2]); $("#projectfk",formid).val(data[3]); $("#structurefk",formid).val(data[4]); $("#client",formid).val(data[5]); $("#clientfk",formid).val(data[6]); if (data[4] === "37") { alert('Multi-client Project; please select client' ) ; $("#tr_client",formid).show(); } } }); // accounts autocomplete // this function is used rarely, only when a deposit is not in payment of an invoice // data is returned as: acctname|acctnamefk|sign|conversion|symbol $("#acctname",formid).autocomplete(searchaccount,{ mustMatch: true }); $("#acctname",formid).result(function(event, data, formatted) { if (data) { $("#acctnamefk",formid).val(data[1]); $("#sign",formid).val(data[2]); $("#conversion",formid).val(data[3]); $("#symbol",formid).val(data[4]); // We will try to set the sign of the account if($("#id_g",formid).val() == "_empty") { // we are in add mode // try to set sign if(Balance) { // The Balance is always stored in the corporate default currency // so the amount of this transaction is equal to the outstanding balance, // times the sign of Master record (1 or -1) // times the sign of Detail record (1 or -1) // times the conversion rate of the Detail record (also most likely to be 1) // times -1, to be the opposite of the Master record var amtval = Balance * parseInt(SeriesSign,10) * parseInt(data[2],10) * parseInt(data[3],10) * (-1); if(!isNaN(amtval)) { amtval = amtval.toFixed(2); $("#amount",formid).val(amtval); } } } } }); }, beforeShowForm : function (formid) { if( ThisTrans == 'X') { var data = $("#tblMaster").getRowData(ThisTrans) ; }; if (Raw !== Balance) { $("#symbol",formid).attr('disabled',true); }; }, afterSubmit : function(data,postdata) { if( 1==1 ) { // increment the global detail counter cntdtl = parseInt(cntdtl,10) + 1; return [true,"","X"+cntdtl]; } else { return [false,"",""]; } }, afterComplete : function(data,postdata,formid) { TransChanged = true; if( CalcNet(ThisTrans) ) { $("#editmod"+"tblDetails").jqmHide(); $("#fullpage_cmdnewbatch").hide(); $("#fullpage_cmdaudittrail").hide(); } if( ThisTrans == 'X') { var data = $("#tblMaster").getRowData(ThisTrans); } $("#acctname",formid).focus(); } } ; // Editing Details records var editdtprm = { width: 500, height: 350, top: 125, left: 50, reloadAfterSubmit:false, closeAfterEdit:false, editCaption : "Edit Distribution Side", onInitializeForm : function (formid){ $("#invoiced",formid).attr('disabled',true); $("#outstanding",formid).attr('disabled',true); $("#invoice",formid).keypress(function(e) {; var keynum ; if(window.event) { // IE keynum = e.keyCode; } else { // Netscape/Firefox/Opera keynum = e.which; }; if (keynum == 13) { var ret = CheckInvoice(formid) } } ) ; $("#invoice",formid).change(function() {; var ret = CheckInvoice(formid) } ) ; // accounts autocomplete // data is returned as: acctname|acctnamefk|sign|conversion|symbol $("#acctname",formid).autocomplete(searchaccount,{ mustMatch: true }); $("#acctname",formid).result(function(event, data, formatted) { if (data) { $("#acctnamefk",formid).val(data[1]); $("#sign",formid).val(data[2]); $("#conversion",formid).val(data[3]); $("#symbol",formid).data[4]; } }); $("#project",formid).after('<span id="prbut"><img src="../images/find.gif" border="0" alt="Find Project"/></span>'); $("#prbut",formid).click(function(){ modal_win('',"Search Projects",{top:60,height:450,width:780,left:50}); $.ajax({ url: "some url", dataType:"html", error: function (req,sttext) { alert(sttext+" : " +req) }, success: function(req) { $("#doc_content","#doc_dialog").html(req); $("#sg_client", "#search_form").autocomplete(searchcv ); $("#tblprojects").setGridParam({ onSelectRow : function (rowid) { var srarray = $("#tblprojects").getRowData(rowid); $("#projectfk",formid).val(srarray.projectpk); $("#project",formid).val(srarray.projectname); $("#projectnumber",formid).val(srarray.projectbumber); $("#shorttitle",formid).val(srarray.shorttitle); $("#structurefk",formid).val(srarray.structurefk); $("#client",formid).val(srarray.client); $("#clientfk",formid).val(srarray.clientfk); if (srarray.structurefk === "37") { alert('Multi-client Project; please select client' ) ; $("#tr_client",formid).show(); } $("#doc_dialog").jqmHide(); } }); } }); }); // Projects autocomplete $("#tr_projectnumber",formid).hide(); $("#tr_shorttitle",formid).hide(); if ($("#structurefk",formid).val !== "37") { $("#tr_client",formid).hide(); }; $("#project",formid).autocomplete(searchproject,{ mustMatch: true }); $("#project",formid).result(function(event, data, formatted) { if (data) { $("#projectnumber",formid).val(data[1]); $("#shorttitle",formid).val(data[2]); $("#projectfk",formid).val(data[3]); $("#structurefk",formid).val(data[4]); $("#client",formid).val(data[5]); $("#clientfk",formid).val(data[6]); if (data[4] === "37") { alert('Multi-client Project; please select client' ) ; $("#tr_client",formid).show(); } } }); }, beforeShowForm : function(formid) { if (Raw !== Balance) { $("#symbol",formid).attr('disabled',true); }; return true; }, afterComplete : function(data,postdata){ // compare the posted data with the grid data // if there is a change set TransChanged to true var detailrec = $("#tblDetails").getRowData(postdata.id); // we do reverse comparing the base is the grid data not postdata // maybe here can be a problems???? $.each(detailrec,function(name,value) { if(postdata[name] !== value) { TransChanged = true; return false; } }); if( CalcNet(ThisTrans) ) { $("#editmod"+"tblDetails").jqmHide(); } } } ; var deldtprm = { reloadAfterSubmit:false, afterComplete : function(data,postdata){ TransChanged = true; CalcNet(ThisTrans); $("#fullpage_cmdnewbatch").hide(); $("#fullpage_cmdaudittrail").hide(); } } ;
Now we do the functions referred to in the grid definitions
function AddMasterTrans(){ if( (parseInt(ThisTrans,10) >= 0 || ThisTrans =='') && TransChanged===false) { $("#tblDetails") .clearGridData() .setCaption("Select an Item, above, to view or edit details here") $("#tblMaster").editGridRow("new",addmasterprm); } else { alert("Save or Cancel Changes before adding"); } } ;

function AddDetail() { if( ThisTrans == 0 || ThisTrans == ''){ alert("Please select Transaction"); } else { $("#tblDetails").editGridRow("new",adddtprm); } };

function FirstRecord(id) { // this is always disabled; $("#fullpage_txtbatch").attr('disabled',true); // Set state of buttons; var mstr = parseInt($("#tblMaster").getGridParam("records"),10); if(mstr === 0) { $("#fullpage_cmdsavetrans").hide(); $("#fullpage_cmdcancel").hide(); $("#fullpage_cmdnewbatch").hide(); $("#fullpage_cmddepositslip").hide(); $("#fullpage_cmdaudittrail").hide(); return true; }; } ;

function CheckMaster() { // Check whenever something is changed to the master ; // and prevent the events in the grid - sorting and paging ; if (TransChanged===true) { ; alert("Save or Cancel Changes before editing another row"); ; var sr = $("#tblMaster").getGridParam('selrow'); ; $("#tblMaster").setGridParam({datatype:'clientSide'}); ; setTimeout(function(){$("#tblMaster").setGridParam({datatype:'xml',selrow:sr});},100); ; return false ; } else { ThisTrans = 0 ; return true ; } ; } ;

function GoToDetails(id) { CalcNet(id) ; if(id == 'X') { var dtls = parseInt($("#tblDetails").getGridParam("records"),10); if(dtls === 0) { // No details, create one (or more, if taxes are involved) if(TaxAmount != 0) { var datarow = {acctnamefk:TaxAccount, sign:TaxSign, amount:TaxAmount, acctname:TaxAccountName, conversion:TaxConversion, symbol:TaxSymbol} ; var su=$('#tblDetails').addRowData('X1',datarow,'last'); CalcNet(id) ; } ; } else { // We have existing details, do nothing alert('dtls = ' + dtls); } } else { // We have existing details, do nothing alert('ID is not = X'); } ; } ;

function CalcNet(id) { Balance = 0; Raw = 0; var total = 0; var data = $("#tblMaster").getRowData(ThisTrans) var regExp = /,/g ; var amt = data.amount.replace(regExp,'') ; Raw += (Number(amt) * SeriesSign) ; total += (Number(amt) * SeriesSign * Conversion) ; // get Value of Detail rows ; var s = $("#tblDetails").getDataIDs(); data = null; $.each(s, function(n, rowid) { data = $("#tblDetails").getRowData(rowid) ; var amt = data.amount.replace(regExp,'') ; var drcr = parseInt(data.sign.replace(regExp,''),10); var exch = parseInt(data.conversion.replace(regExp,''),10); Raw += (Number(amt) * drcr) ; total += (Number(amt) * drcr * exch) ; }); ctotal = total.toFixed(2) ; $("#fullpage_cmdcancel").show(); if( ctotal == 0 ) { $("#tblDetailsMessage").html("This transaction is in balance") ; $("#fullpage_cmdsavetrans").show(); In_Balance = true; } else { var nf = new NumberFormat(ctotal); nf.setCurrencyValue('$'); nf.setCurrency(true); var num = nf.toFormatted(); $("#tblDetailsMessage").html("Transaction's net amount = " + num) ; $("#fullpage_cmdsavetrans").hide(); In_Balance = false; } Balance = total; if (Raw == Balance) { $("#tblDetails").hideCol("symbol") ; } else { $("#tblDetails").showCol("symbol") ; } return In_Balance; } ;

function PostTrans() { var regExp = /,/g ; var postdata = ' '; // Common data (from the form) first postdata += 'period:' + $("#fullpage_cboperiod").val() + ',' ; postdata += 'date:' + $("#fullpage_txtdate").val() + ','; postdata += 'batch:' + $("#fullpage_txtbatch").val() + ','; var exchange = Raw - Balance; postdata += 'exchange:' + exchange + ','; // Bank side from the Master grid var Mrow = $("#tblMaster").getGridParam("selrow") ; var data = $("#tblMaster").getRowData(Mrow) ; postdata += '~pk:' + data.pk + ','; postdata += 'trans:' + data.trans + ','; // This comes from the form but applies only to the master grid data postdata += 'stdacctfk:' + $("#fullpage_cboaccount").val() + ','; postdata += 'cheque:' + data.cheque + ','; postdata += 'issued:' + data.issued + ','; postdata += 'vendor:' + data.cvfk + ','; postdata += 'amount:' + data.amount.replace(regExp,'') + ','; postdata += 'comment:' + data.comment + ','; // Distribution entry(ies) from the Details grid s = $("#tblDetails").getDataIDs(); $.each(s, function(n, rowid) { var data = $("#tblDetails").getRowData(rowid) ; postdata += '~pk:' + data.pk + ',' ; postdata += 'invoice:' + data.invoice + ','; postdata += 'project:' + data.projectfk + ','; postdata += 'acctnamefk:' + data.acctnamefk + ','; postdata += 'amount:' + data.amount.replace(regExp,'') + ','; postdata += 'comment:' + data.comment + ','; }); // Post it all $.post( posturl, postdata,function(message,status) { if(status !== 'success') { alert(message); } else { if(message !== '<html>') { // Message contains the batch number $("#fullpage_txtbatch").val(message) ; $("#fullpage_cboaccount").attr('disabled',true) ; $("#fullpage_txtdate").attr('disabled',true) ; $("#fullpage_cboperiod").attr('disabled',true) ; $("#fullpage_cmdsavetrans").hide(); $("#fullpage_cmdcancel").hide(); $("#fullpage_cmdnewbatch").show(); $("#fullpage_cmddepositslip").show(); $("#fullpage_cmdaudittrail").show(); // clear the messages $("#tblDetailsMessage").html(""); // Reload Master Grid $("#tblMaster").setGridParam({url:masterurl + "&amp;Batch=" + message}); $("#tblMaster").trigger('reloadGrid'); ThisTrans = 0; TransChanged = false; $("#tblDetails") .clearGridData() .setCaption("Select an Item, above, to view or edit details here") } else { // Save returned nothing useful alert(message); }; }; } ); };

function CancelTrans() { // Reload Master Grid var batch = $("#fullpage_txtbatch").val(); $("#tblMaster").setGridParam({url:masterurl + "&amp;Batch=" + batch}); $("#tblMaster").trigger('reloadGrid'); ThisTrans = 0; TransChanged = false; // Clear Details Grid $("#tblDetails") .clearGridData() .setCaption("Select an Item, above, to view or edit details here") $("#tblDetailsMessage").html(""); // Reset the buttons $("#fullpage_cmdsavetrans").hide(); $("#fullpage_cmdcancel").hide(); var mstr = parseInt($("#tblMaster").getGridParam("records"),10); if(mstr === 0) { $("#fullpage_cmdnewbatch").hide(); $("#fullpage_cmddepositslip").hide(); $("#fullpage_cmdaudittrail").hide(); } else { $("#fullpage_cmdnewbatch").show(); $("#fullpage_cmddepositslip").show(); $("#fullpage_cmdaudittrail").show(); }; } ;

function CheckInvoice(formid) { var invno = 'invoice=' + $("#invoice",formid).val() ; if (invno == 'invoice=') { $("#tr_invoiced",formid).hide(); $("#tr_outstanding",formid).hide(); $("#acctname",formid).attr('disabled',false); $("#project",formid).attr('disabled',false); $("#tr_comment",formid).show(); $("#tr_projectnumber",formid).show(); $("#tr_shorttitle",formid).show(); $("#tr_client",formid).show(); alert("Payment not against an Invoice; please enter details") } else { $.getJSON(searchinvoice, invno, function(data) { if (data.status == 'No match found; please try again') { alert(data.status) } else { // data is returned as: Invoice #|Invoiced|OS|acctname|acctnamefk|sign|conversion|symbol|Project // Load, show and disable the fields we know about $("#invoiced",formid).val(data.invoiced); $("#outstanding",formid).val(data.os); $("#acctname",formid).val(data.acctname); $("#acctnamefk",formid).val(data.acctnamefk); $("#sign",formid).val(data.sign); $("#conversion",formid).val(data.exchange); $("#symbol",formid).val(data.symbol); $("#project",formid).val(data.project); $("#projectfk",formid).val(data.projectfk); $("#acctname",formid).attr('disabled',true); $("#project",formid).attr('disabled',true); $("#tr_invoiced",formid).show(); $("#tr_outstanding",formid).show(); $("#tr_acctname",formid).show(); // Hide unneeded fields $("#tr_comment",formid).hide(); $("#tr_projectnumber",formid).hide(); $("#tr_shorttitle",formid).hide(); $("#tr_client",formid).hide(); var regExp = /,/g ; var Outstanding = Number(data.os.replace(regExp,'')); var Available = Balance * -1 ; if (Available > Outstanding ) { var Payment = Outstanding * -1 } else { var Payment = Available * -1 }; $("#amount",formid).val(Payment) ; var Mrow = $("#tblMaster").getGridParam('selrow') ; var CurrentData = $("#tblMaster").getRowData(Mrow) ; var ClientFK = CurrentData.cvfk ; var NClientFK = Number(ClientFK); if (NClientFK == 0 ) { // We do not yet have a client, so store the new value $("#tblMaster").setRowData(Mrow,{cvname:data.client, cvfk:data.clientfk}) } else { // We already have a client; is this the same one? if (ClientFK !== data.clientfk) { // Payors are different, so ask if(confirm("Change Payor from " + CurrentData.cvname + " to " + data.client)) { $("#tblMaster").setRowData(Mrow,{cvname:data.client, cvfk:data.clientfk } ) } else { alert("Payor left unchanged, as " + CurrentData.cvname) } } } } }) } };

Finally, the supporting settings for DatePicker.
$.datepicker.regional['en'] = { // Default regional settings dateFormat: 'yy/mm/dd', // See format options on parseDate firstDay: 0 // The first day of the week, Sun = 0, Mon = 1, ... }; $.datepicker.setDefaults($.datepicker.regional['en']); AdjustContentHeight(); document.fullpage.fullpage_cboaccount.focus(); });


  Last Updated: 2/23/2009 | © Tony's jqGrid - a jQuery Plugin, 2010