forked from jpederson/Accrue.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.accrue.js
500 lines (407 loc) · 20.5 KB
/
jquery.accrue.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/*
* Accrue.js
* http://accruejs.com
* Author: James Pederson (jpederson.com)
* Licensed under the MIT, GPL licenses.
* Version: 1.1.0
*/
;(function( $, window, document, undefined ){
// let's start our plugin logic
$.extend($.fn, {
accrue: function( options ){
// set our options from the defaults, overriding with the
// parameter we pass into this function.
options = $.extend( { calculationMethod: calculateBasic }, $.fn.accrue.options, options );
// Iterate through all the matching elements and return
// the jquery object to preserve chaining.
return this.each(function(){
// Store a jQuery object for our element so we can use it
// inside our other bindings.
var elem = $(this);
// Create the form div if it doesn't exist.
if ( !elem.find(".form").length ) {
elem.append( '<div class="form"></div>' );
}
// Get the amount, rate(s), and term - and clean the values
var amount = get_field( elem, options, "amount" );
var rate = get_field( elem, options, "rate" );
var term = get_field( elem, options, "term" );
// If we're in comparison mode, grab an additiona field/value.
if ( options.mode=="compare" ) {
var rate_compare = get_field( elem, options, "rate_compare" );
}
// If we are using the default results div and it doesn't exist, create it.
var output_elem;
if ( options.response_output_div === ".results" ) {
if ( elem.find(".results").length === 0 ) {
elem.append('<div class="results"></div>');
}
// Set the output div as a variable so we can refer to it more easily.
output_elem = elem.find(".results");
} else {
// Set the output div as a variable so we can refer to it more easily.
output_elem = $(options.response_output_div);
}
// Set the calculation method based on which mode we're in.
var calculation_method;
switch ( options.mode ) {
case "basic":
calculation_method = calculateBasic;
break;
case "compare":
calculation_method = calculateComparison;
break;
case "amortization":
calculation_method = calculateAmortization;
break;
}
// Get the information about the loan.
calculation_method( elem, options, output_elem );
// Do some different things if the operation mode is "button"
if ( options.operation=="button" ) {
// If we are using button operation mode and the button doesn't exist, create one.
if ( elem.find("button").length === 0 && elem.find("input[type=submit]").length === 0 && elem.find("input[type=image]").length === 0 ) {
elem.find(".form").append('<button class="accrue-calculate">'+options.button_label+'</button>');
}
// If the developer has chosen to bind to a button instead
// of operate on keyup, let's set up a click event binding
// that performs the calculation.
elem.find("button, input[type=submit], input[type=image]").each(function(){
$(this).click(function( event ){
event.preventDefault();
calculation_method( elem, options, output_elem );
});
});
} else {
// Bind to the select and input elements so that we calculate
// on keyup (or change in the case of the select list).
elem.find("input, select").each(function(){
$(this).bind( "keyup change", function(){
calculation_method( elem, options, output_elem );
});
});
}
// If the developer has chosen to bind to a button instead
// of operate on keyup, let's set up a click event binding
// that performs the calculation.
elem.find("form").each(function(){
$(this).submit(function(event){
event.preventDefault();
calculation_method( elem, options, output_elem );
});
});
});
}
});
// DEFAULTS
// Set up some default options for our plugin that can be overridden
// as needed when we actually instantiate our plugin on a form.
$.fn.accrue.options = {
mode: "basic",
operation: "keyup",
default_values: {
amount: "$7,500",
rate: "7%",
rate_compare: "1.49%",
term: "36m"
},
field_titles: {
amount: "Loan Amount",
rate: "Rate (APR)",
rate_compare: "Comparison Rate",
term: "Term"
},
button_label: "Calculate",
field_comments: {
amount: "",
rate: "",
rate_compare: "",
term: "Format: 12m, 36m, 3y, 7y"
},
response_output_div: ".results",
response_basic:
'<p><strong>Monthly Payment:</strong><br />$%payment_amount%</p>'+
'<p><strong>Number of Payments:</strong><br />%num_payments%</p>'+
'<p><strong>Total Payments:</strong><br />$%total_payments%</p>'+
'<p><strong>Total Interest:</strong><br />$%total_interest%</p>',
response_compare: '<p class="total-savings">Save $%savings% in interest!</p>',
error_text: '<p class="error">Please fill in all fields.</p>',
callback: function ( elem, data ){}
};
// FORMAT MONEY
// This function is used to add thousand seperators to numerical ouput
// as a means of properly formatting money
function formatNumber (num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}
// GET FIELD
// A function just for grabbing the value from a particular field.
// We need this because if the field doesn't exist, the plugin will
// create it for them.
var get_field = function( elem, options, name ) {
// Check for an input with a class of the name.
var field;
if ( elem.find(".accrue-"+name).length ) { // if has a class of accrue-[name]
field = elem.find(".accrue-"+name);
} else if ( elem.find("."+name).length ) { // if we have class of just the name
field = elem.find("."+name);
} else if ( elem.find( "input[name~="+name+"]" ).length ) {
elem.find( "input[name~="+name+"]" );
} else {
field = "";
}
// If we have the field value, return it right away so that the
// calculator doesn't write the field to the form div since we
// don't need it to.
if ( typeof( field ) !== "string" ) {
return field.val();
}
if ( name == "term_compare" ) {
return false;
}
// If we've gotten here, no fields were found that match the
// criteria. Create the form field and return the default value.
elem.find(".form").append(
'<div class="accrue-field-'+name+'">'+
'<p><label>'+options.field_titles[name]+':</label>'+
'<input type="text" class="'+name+'" value="'+options.default_values[name]+'" />'+
( options.field_comments[name].length>0 ? "<small>"+options.field_comments[name]+"</small>" : '' )+'</p>'+
'</div>');
return elem.find("."+name).val();
};
// CALCULATE BASIC
// for the basic calculation, we're just getting the values and
// calculating loan info for a single loan.
var calculateBasic = function( elem, options, output_elem ){
// get the loan information from the current values in the form.
var loan_info = $.loanInfo({
amount: get_field( elem, options, "amount" ),
rate: get_field( elem, options, "rate" ),
term: get_field( elem, options, "term" )
});
// if valid, output into the output_elem that was passed into this function.
if ( loan_info!==0 ) {
// replace the placeholders with the response values.
var output_content = options.response_basic
.replace( "%payment_amount%", formatNumber(loan_info.payment_amount_formatted) )
.replace( "%num_payments%", loan_info.num_payments )
.replace( "%total_payments%",formatNumber(loan_info.total_payments_formatted) )
.replace( "%total_interest%", formatNumber(loan_info.total_interest_formatted) );
// output the content to the actual output element.
output_elem.html( output_content );
} else {
// if the values for the loan calculation aren't valid, provide an error.
output_elem.html( options.error_text );
}
// run the callback function after the calculation is done, including
// the calculation info so it's available in the callback.
options.callback( elem, loan_info );
};
// CALCULATE COMPARE
// The comparison mode gets 4 values from the form and calculates, then
// compares two different loans to determine savings in interest.
var calculateComparison = function( elem, options, output_elem ){
// see if there's a comparison term
var term_compare = get_field( elem, options, "term_compare" );
// if the comparison term is empty, use the normal term field
if ( typeof( term_compare ) == "boolean" ) {
term_compare = get_field( elem, options, "term" );
}
// Get information about the two different loans in question
// and create a callback data variable that we'll pass into
// our callback function.
var loan_1_info = $.loanInfo({
amount: get_field( elem, options, "amount" ),
rate: get_field( elem, options, "rate" ),
term: get_field( elem, options, "term" )
}),
loan_2_info = $.loanInfo({
amount: get_field( elem, options, "amount" ),
rate: get_field( elem, options, "rate_compare" ),
term: term_compare
}),
callback_data = {
loan_1: loan_1_info,
loan_2: loan_2_info
};
// If both loans are good, populate response element with info,
// else error.
if ( loan_1_info!==0 && loan_2_info!==0 ) {
if ( loan_1_info.total_interest-loan_2_info.total_interest > 0 ) {
callback_data.savings = loan_1_info.total_interest-loan_2_info.total_interest;
} else {
callback_data.savings = 0;
}
// replace our savings placeholder in the response text with
// the real difference in interest.
var output_content = options.response_compare
.replace( "%savings%", formatNumber(callback_data.savings.toFixed(2)) )
.replace( "%loan_1_payment_amount%", formatNumber(loan_2_info.payment_amount_formatted) )
.replace( "%loan_1_num_payments%", loan_2_info.num_payments )
.replace( "%loan_1_total_payments%", loan_2_info.total_payments_formatted )
.replace( "%loan_1_total_interest%", formatNumber(loan_2_info.total_interest_formatted) )
.replace( "%loan_2_payment_amount%", formatNumber(loan_1_info.payment_amount_formatted) )
.replace( "%loan_2_num_payments%", loan_1_info.num_payments )
.replace( "%loan_2_total_payments%", loan_1_info.total_payments_formatted )
.replace( "%loan_2_total_interest%", formatNumber(loan_1_info.total_interest_formatted) );
output_elem.html( output_content );
} else {
// output an error
output_elem.html( options.error_text );
}
// run the callback, passing our loan data into it.
options.callback( elem, callback_data );
};
// CALCULATE AMORTIZATION SCHEDULE
// This method outputs a table with the repayment schedule
// for a single loan object.
var calculateAmortization = function( elem, options, output_elem ){
// Get the loan information so we can build out our amortization
// schedule table.
var loan_info = $.loanInfo({
amount: get_field( elem, options, "amount" ),
rate: get_field( elem, options, "rate" ),
term: get_field( elem, options, "term" )
});
// If the loan info's good, start buildin'!
if ( loan_info!==0 ) {
// Set some initial variables for the table header, interest
// per payment, amount from balance, and counter variables
// to values as we list rows.
var output_content = '<table class="accrue-amortization">'+
'<thead><tr>'+
'<th class="accrue-payment-number">#</th>'+
'<th class="accrue-payment-amount">Payment Amt.</th>'+
'<th class="accrue-total-interest">Total Interest</th>'+
'<th class="accrue-total-payments">Total Payments</th>'+
'<th class="accrue-balance">Balance</th>'+
'</tr></thead><tbody>',
interest_per_payment = loan_info.payment_amount-(loan_info.original_amount/loan_info.num_payments),
amount_from_balance = loan_info.payment_amount-interest_per_payment,
counter_interest = 0,
counter_payment = 0,
counter_balance = parseInt(loan_info.original_amount, 10);
// Start appending the table rows to our output variable.
for ( var i=0; i<loan_info.num_payments; i++) {
// Record the payment in our counter variables.
counter_interest = counter_interest+interest_per_payment;
counter_payment = counter_payment+loan_info.payment_amount;
counter_balance = counter_balance-amount_from_balance;
// bold the last row of the table by using <th>s for
// the values.
var cell_tag = "td";
if ( i==(loan_info.num_payments-1) ) {
cell_tag = "th";
}
// Append a row to the table
output_content = output_content+
'<tr>'+
'<'+cell_tag+' class="accrue-payment-number">'+(i+1)+'</'+cell_tag+'>'+
'<'+cell_tag+' class="accrue-payment-amount">$'+formatNumber(loan_info.payment_amount_formatted)+'</'+cell_tag+'>'+
'<'+cell_tag+' class="accrue-total-interest">$'+formatNumber(counter_interest.toFixed(2))+'</'+cell_tag+'>'+
'<'+cell_tag+' class="accrue-total-payments">$'+formatNumber(counter_payment.toFixed(2))+'</'+cell_tag+'>'+
'<'+cell_tag+' class="accrue-balance">$'+formatNumber(counter_balance.toFixed(2))+'</'+cell_tag+'>'+
'</tr>';
}
// Finish off our table tag.
output_content = output_content+
'</tbody></table>';
// Push our output content into the output element.
output_elem.html( output_content );
} else {
// Values aren't good yet, show the error.
output_elem.html( options.error_text );
}
// Execute callback, passing in loan information.
options.callback( elem, loan_info );
};
// BASIC LOGGING FUNCTION
// Checks to see if the console is available before outputting
// anything through console.log(). Prevent issues with IE.
var log = function( message ){
if ( window.console ) {
console.log( message );
}
};
// GENERAL LOAN INFORMATION FUNCTION
// This is the public function we use inside our plugin function
// and we're exposing it here so that we can also provide generic
// calculations that just return JSON objects that can be used
// for custom-developed plugins.
$.loanInfo = function( input ) {
var amount = ( typeof( input.amount )!=="undefined" ? input.amount : 0 ).toString().replace(/[^\d.]/ig, ''),
rate = ( typeof( input.rate )!=="undefined" ? input.rate : 0 ).toString().replace(/[^\d.]/ig, ''),
term = ( typeof( input.term )!=="undefined" ? input.term : 0 );
// parse year values passed into the term value
if ( term.match("y") ) {
term = parseInt( term.replace(/[^\d.]/ig, ''), 10 )*12;
} else {
term = parseInt( term.replace(/[^\d.]/ig, ''), 10 );
}
// process the input values
var monthly_interest = rate / 100 / 12;
// Now compute the monthly payment amount.
var x = Math.pow(1 + monthly_interest, term),
monthly = (amount*x*monthly_interest)/(x-1);
// If the result is a finite number, the user's input was good and
// we have meaningful results to display
if ( amount*rate*term>0 ) {
// Fill in the output fields, rounding to 2 decimal places
return {
original_amount: amount,
payment_amount: monthly,
payment_amount_formatted: monthly.toFixed(2),
num_payments: term,
total_payments: ( monthly * term ),
total_payments_formatted: ( monthly * term ).toFixed(2),
total_interest: ( ( monthly * term ) - amount ),
total_interest_formatted: ( ( monthly * term ) - amount ).toFixed(2)
};
} else {
// The numbers provided won't provide good data as results,
// so we'll return 0 so it's easy to test if one of the fields
// is empty or invalid.
return 0;
}
};
// REVERSE LOAN INFORMATION FUNCTION
// This is a copy of the above, only that given a payment amount, rate and term it
// will return the principal amount that can be borrowed.
$.loanAmount = function( input ) {
var payment = ( typeof( input.payment )!=="undefined" ? input.payment : 0 ).toString().replace(/[^\d.]/ig, ''),
rate = ( typeof( input.rate )!=="undefined" ? input.rate : 0 ).toString().replace(/[^\d.]/ig, ''),
term = ( typeof( input.term )!=="undefined" ? input.term : 0 );
// parse year values passed into the term value
if ( term.match("y") ) {
term = parseInt( term.replace(/[^\d.]/ig, ''), 10 )*12;
} else {
term = parseInt( term.replace(/[^\d.]/ig, ''), 10 );
}
// process the input values
var monthly_interest = rate / 100 / 12,
annual_interest = rate / 100;
// Now compute.
var x = payment * (1 - Math.pow(1 + monthly_interest, -1 * term)) * (12/(annual_interest));
// If the result is a finite number, the user's input was good and
// we have meaningful results to display
if ( x>0 ) {
// Fill in the output fields, rounding to 2 decimal places
return {
principal_amount: x,
principal_amount_formatted: ( x * 1 ).toFixed(2),
payment_amount: payment,
payment_amount_formatted: ( payment * 1 ).toFixed(2),
num_payments: term,
total_payments: ( payment * term ),
total_payments_formatted: ( payment * term ).toFixed(2),
total_interest: ( ( payment * term ) - x ),
total_interest_formatted: ( ( payment * term ) - x ).toFixed(2)
};
} else {
// The numbers provided won't provide good data as results,
// so we'll return 0 so it's easy to test if one of the fields
// is empty or invalid.
return 0;
}
};
})( jQuery, window, document );