Working with money in JavaScript

Here are some great techinques that I have come up with while working as paperless applications developer at SVC:

Working with money can require a lot of scripts to ensure sucessful data entry , transfer and saving.

One thing that comes up is the errors that users can make when entering the figures for money into a form. The forms will have many different requirements for entering the monetary information, such as type of figures desired. For example, on one form, I need the user to only enter a whole dollar amount, and I need to make sure that no dollar signs, cent signs or punctuation make it into the calculations for totals.

Here is a script to clean an entry of all dollar signs, cent signs,  punctuation  and ensure that whole dollar amounts are entered. For this usage, I have set up the function to be passed a Jquery object of a textfield , and the function will get the value, fix it and put it back in.
[code language=”javascript”]
// strip out any $$ .00 and anything else
function stripper(who){
dirtynumber = $( who ).val();
cleannumber = parseInt(dirtynumber.replace(/[^d.]/g, “”));
if(isNaN(cleannumber)){cleannumber=0;}
$( who ).val(cleannumber); }
[/code]

Here is a script to compare two values to make sure they are the same:

[code language=”html”]
// ensure budget items total match budget request
var amount1 =  parseInt($(“#fund_request”).val().replace(/[^d.]/g, “”));
var amount2 =  parseInt($(“#justification_budget_total”).val().replace(/[^d.]/g, “”));
if(isNaN(amount1)){amount1=0}
if(isNaN(amount2)){amount2=0}
if(amount1 !== amount2){alert(“The total budget request : ” + amount1 + ” doesn’t equal the budget justification item total: ” + amount2 + “. Please check your numbers and re submit.”);return false;}
[/code]

Using Browser console for debugging Test Driven JavaScript

One of the great things about TTD is the ability to track the success of each action in the application, whether it was user initiated or an automatic application function. For me, so far, one of the best ways to do this is using the debug console built into the browser. Each browser is specific, of course, but there is a simple technique to use the code cross browser without generating errors.

if(!window.console){ window.console = {log: function(){} }; }

An example of usage is in my form content wizard plugin.

  // look into step for custom button, then add the "begin" button to the first step if not there.
 if(!beginbuttonclass){ 
var beginbuttonclass=""; 
console.log('Note from content display wizard plugin: beginbuttonclass has not been defined. See documentation for more information.');}

To see if an external  script is loaded sucessfully, you need to have a variable that the script would provide, then check for it. For example here we will try see if  I have successfully  loaded JQuery from the cdn: (code.jquery.com/jquery-1.10.2.min.js)

try {
     if($()){console.log("Message from slider admin: Jquery loaded... now executing document load functions...");} 
} catch (e) { console.log("Message from slider admin, error loading jquery..."+e.message); }

 

Working with dates and times in JavaScript

I need to get the current year and display it in a form. That way the form doesn’t have to be updated every year, just to change the date.

We always start with a date object, then use it to get what we need.

var today = new Date();
var theyear = today.getFullYear();
$("#theyear").html(theyear); // put the variable into a span with id of "theyear"

I would like to have a form that auto fills todays date in the following format: 2/27/2014

var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
document.write(month + "/" + day + "/" + year);

Here are great docs and examples from Mozilla

Saving user data with cookies

The user needs to have a small amount of data saved so they don’t have to fill the same fields of a form out over and over. The best way to do this would be with a cookie set for the life of the form, for example, they will fill out a form frequently for three months, entering their name and personal info over and over. So, lets allow them to save the info, on click of a button, and load it in on return visits to the form.

I can set cookies with javascript or server side code. In this case I think that js would be the best. We need to have some basic functions for setting and getting cookies…

function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(” ” + c_name + “=”);
if (c_start == -1)
{
c_start = c_value.indexOf(c_name + “=”);
}
if (c_start == -1)
{
c_value = null;
}
else
{
c_start = c_value.indexOf(“=”, c_start) + 1;
var c_end = c_value.indexOf(“;”, c_start);
if (c_end == -1)
{
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
} // end get cookie function

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? “” : “; expires=”+exdate.toUTCString());
document.cookie=c_name + “=” + c_value;
} // end set cookie function

Once we have our basic cookie setting, reading and deleting functions, we can set up a function to save the user’s data, called when they click a button…

function saveInfo(){
//alert(‘lets gather the data and save to cookie’);
var nominator_firstname = $(“#nominator_firstname”).val();
var nominator_lastname = $(“#nominator_lastname”).val();
var nominator_org = $(“#nominator_org”).val();
var nominator_title = $(“#nominator_title”).val();
var nominator_address = $(“#nominator_address”).val();
setCookie(“nominator_firstname”,nominator_firstname,90);
setCookie(“nominator_lastname”,nominator_lastname,90);
setCookie(“nominator_org”,nominator_org,90);
setCookie(“nominator_title”,nominator_title,90);
setCookie(“nominator_address”,nominator_address,90);
alert(” Nominator Info Saved for 90 days”);
}

 

When the user comes back to the page,  I can check for the cookies and put them into the right place in the form using this function:

function checkCookie()
{
var nominator_firstname=getCookie(“nominator_firstname”);
var nominator_lastname=getCookie(“nominator_lastname”);
if (nominator_firstname!=null && nominator_firstname!=””) { $(“#nominator_firstname”).val(nominator_firstname); }
if (nominator_lastname!=null && nominator_lastname!=””) { $(“#nominator_lastname”).val(nominator_lastname); }

} // end check cookie function

Efficient JavaScript Best Practice:Arrays

I am going to research and document best practice to use js arrays.

Declare an array in JavaScript:

var myarray = [];

To assign a value to the array:

myarray[0] = “The first value”;
myarray[1] = “The second value”;

to insert a value at end of array:

myarray.push(“The third value”);
myarray.push(“The fourth”, “The fifth”);

The array.toString() will list the variables separated by a comma

 

 

Suppose I have a list of items that I would like to put into an array:


myarrayfromlist=[];
  • My list item one
  • My list item two
  • My list item three

$("#mylist li").each(
   function(){
     myarrayfromlist.push($(this).html())
  }
);

 

For a less complex situation where you don’t need custom keys, a standard array can be written as so… var coinsIhave = [1950, 1960, 1970, 1980, 1990, 2000, 2010];

then coinsIhave[0] is  1950.

How to I access the key of an item in the array, for example, what key is 1980?
Well, unfortunatley JavaScript doesn’t have a function for that. We can make our own, and in a less complex scenario, this would be ok.

[code]function findKey(whatkey, whatarray){
for(a=0;a<whatarray.length;a++){
if(whatarray[a].id==whatkey){
$(“#debuglog”).append(“<p>Array Item:”+whatarray[a].id+” || Key: ” + a +”</p>”);
return a;}
}

}[/code]

So if I were to execute findKey(coinsIhave, ‘1980’) it would return 3.

But if I want to know what kind of coin it is, as well as the year, I would like to use a dictionary object or associated array.

var coinsIhave=new Object();
coinsIhave.silverdollar=”1950″;
coinsIhave.centenialquarter=”1960″;

Although they can be called associated arrays, we are creating a JavaScript object and assigning properties. These properties can be assigned and accessed using dot or bracket notation. It is important to note that any property name that is not a valid JavaScript identifier (for example, a property name that has space or dash, or starts with a number) can only be accessed using the square bracket notation. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FWorking_with_Objects#Indexing_object_properties

 

It is possible to “fake” a multidimensional array in JavaScript, using notation such as this:

var thecollegechoices=[[“CWU”,”Central University”], [“EWU”,”Eastern Wa University”]];

You would then access the data as so:

thecollegechoices[0][0] would contain the text “CWU”
thecollegechoices[0][1] would contain the text “Central University”
thecollegechoices[1][0] would contain the text “EWU”
thecollegechoices[1][1] would contain the text “Eastern Wa University”

So as we loop through the index of the array, we see the pattern that the abreviations would be in the 0, and the college name would be in the 1. This is going to come in very handy over the course of project development.

After reading the mozzilla docs, I have found a great way to loop through the array to use the items in the array:
[code]

var a = [“dog”, “cat”, “hen”];
for (var i = 0, item; item = a[i++];) {
// Do something with item
console.log(item);
}

[/code]

Note that this trick should only be used for arrays which you know do not contain “falsy” values (arrays of objects or DOM nodes for example). If you are iterating over numeric data that might include a 0 or string data that might include the empty string you should use the i, len idiom instead:

[code]
for (var i = 0, len = a.length; i < len; i++) {
// Do something with a[i]
}[/code]

[code]for (var i in a) {
// Do something with a[i]
}[/code]

Timing events with javascript

The window.setTimeout() can trigger functions and events after a certain amount of time. Using them takes a certain technique that can take a while to master. I always liked to use flash for timing events and animations in my webpage, but we are in a new era with html 5 and browser scripting, so here we go.

The correct technique is to create a timeout object in a variable as so…

var booter = window.setTimeout(function(){alert('boot em out!');},10000);

you could then cancel the timed event with…

window.clearTimeout(booter);

However there is a problem with trying to call the clearTimeout() that was set in a function.

function LogTime() { var booter = setTimeout(function(){  alert('close pop and logout.change the time to 4  minutes'); }, 4000);  }// end log time function

 

When I try to cancel this from another script outside the function, The error that “timer is undefined” is really frustrating.

The key to solving this is to declare the booter variable outside the function, and then use the variable in the function.

var booter; function LogTime() { booter = setTimeout(function(){  alert('close pop and logout.change the time to 4  minutes'); }, 4000);  }// end log time function 

Now this code works well, and the timed event can be  cancelled when I want it to.

So need timer to loop every second.
var mytimer; function timeHer(){mytimer = setInterval(function(){//do something here every second}, 1000);}

Search for a string using Javascript

if (str.indexOf("Yes") >= 0)

 

This is a powerful tool. The variable str contains the text you want to search. “Yes” is an example of what you could search for. It will be >=0 if the string is found in the search.

 

Here is a good example for how to see if its a negative number.

var isnegative=number.indexOf("-")>=0? true : false ;

 

If string passed in is like  number= 10 will return true
If number = -10 then will return false.

 

While enjoying some reading of the Mozilla Developer Network docs, I have stumbled on to a bit of “best practice” techniques:

Note that ‘0’ doesn’t evaluate to true and ‘-1’ doesn’t evaluate to false. Therefore, when checking if a specific string exists within another string the correct way to check would be:

"Blue Whale".indexOf("Blue") != -1; // true
 "Blue Whale".indexOf("Bloe") != -1; // false

So my final snippet for checking if a string is in another string is as follows.

var mystring - "Yes I want to respond."; If (mystring.indexOf("Yes") != -1){console.log("They want to respond");)}