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]

3DW Tools CSS Styles Library

After three years of  designing proof of concept and rapid prototypes I have decided to compile all of my custom css styles that were spread between multiple projects into one master library of css style design patterns. My 3DW Tools CSS Styles Library is managed via my cms, and when included into a project,  grants  access to some really great styles that can be  called using an easy to remember  style language.

In order to produce HTML 5 designs without Flash or Photo Shop, my 3DW Tools CSS Styles Library is the perfect addition to a blank HTML 5 page or a  JQuery build, giving me the ability to design some really great mockups, proof of concept, rapid prototype, and user experience designs.

Here is the link to the visual reference.

Here is a css box shadow generator https://developer.mozilla.org/en-US/docs/Web/CSS/Tools/Box-shadow_generator

Here is a css button generator https://developer.cdn.mozilla.net/media/uploads/demos/m/o/mok20123/8aff6ca4f35726d64880dd6fc77739ba/css3-button-generato_1325474481_demo_package/index.html

Here is the css border radius generator https://developer.mozilla.org/en-US/docs/Web/CSS/Tools/Border-radius_generator

CSS Transformation Matrix Examples

I know that the specs are still experimental, but the support for CSS 3 transformations has reached to all of the major browsers, with millions of combined users accessing the web through them.

The basic transformation matrix function is transform: matrix();

You use this in a style declaration as so…

#mydiv{ transform: matrix(1, 0, 0, 1, 10, 10); }

This would position the div as if you used  left:10 px; top:10px;  but it is way more awesome than that.

Here is a css gradients playground.

 

 

Technical Instructions: How to use my Form Content Display Wizard

So, to use my plugin to any form or content,

Separate content chunks:
Wrap the content in div containers with unique ids begining with “step_xxx”  where xxx should be a detailed way to identify the content such as “step_intro” and  “step_personal_info”

If the path is non branching, the plugin will create buttons for “back” and “next” named “stepDownButton” and “stepUpButton” . It will look for the second to last step and put a submit, and the last step is the confirmation. To create a custom path, branch, or skip a step, just create a button named “stepDownButton” and “stepUpButton” . Give the button an onclick of stepUp(‘stepname’) or stepDown(‘stepname’) to make the button skip to a certain step.

Table of contents
The plugin will use the first element inside the step as description for the table of contents. You can use the attribute stepdesc on the step_xxx element as a custom title for the toc. The toc will be appended to the first step unless you make a custom toc using a container with id of “tableofcontents”. This can be disabled by …..

Form elements and Validation
To provide “empty field” validation to form elements in a step, just add the class “required” to the element. Place the class “email” to validate an email address on one input element. You can add class “match” to two elements in a step and they will have to match each other. Give the elements a unique ID and a good name attribute, and the plugin will create placeholders for the text input elements from the name.
NOTE: it seems like the name attribute is the perfect place to put a readable descriptive title that could be used in creating the labels, and for  summary display. NOTE: it seems like moving to the new html5 text inputs for validation such as email tel, then if input type = email, wouldn’t need a class selector.Just a thought for moving forward with

Data summary
In the second to last step, the plugin will set the the “NEXT” button onclick to stepUp(‘submit’);  The plugin will add a summary of the data the user entered so they may go back and make any changes. You may choose a custom display of the summary by putting an element with id “formsummaryarea” into this step. The plugin will omit any empty or hidden fields from the summary, and you can put class “nosummary” to omit any other items from the summary.

Submit and final confirm
In the final step, you should place your  final confirmation text there. This will tell the user the results of their data submit, success or error.  When user is ready, the script will submit the form data, and move to the final confirmation.

 

 

Themeing the elements

To theme the elements, just add classes to items in the ui view using jquery :

This will add a Panel effect to the divs—
$(‘div[id^=”step_”]’).addClass(“softblackgradient blackbottomrightboxshadow mediumallaroundpadding”);

The buttons wont work to style this way cause they aren’t in dom yet. To theme the buttons, you need to  set these global variables before you call to include the plugin.:

I feel that the “Begin”  button should look very different from the Next and Back buttons:
beginbuttonclass = “button roundedcorners success mediumallaroundpadding”

Here is to style the step up and step down buttons:
stepupbuttonclass=”button oval success smallallaroundpadding”
stepdownbuttonclass=”button oval alert smallallaroundpadding”

The “Submit” button needs to also look very different from the step up and down buttons.
style it like this: submitbuttonclass=”button roundedcorners mediumallaroundpadding success”

 

If you have put in custom buttons to go to non linear paths, make sure to still give the the names of stepUpButton and stepDownButton. Then you can select and style them as well using the jquery selector.

Theres tableofcontents to layout the toc, and  highlightstep to control the highlighted step. This is proving very difficult to get out of the plugin, since the toc relies on the scripts. There are classes yellowhighlight, and  mediumtext that will need to be declared in the ui view that is using the plugin.

Filter text before it is displayed. Find and replace invalid charaters from cms content using JavaScript and ASP

The content for the website is generated by the staff and put into the site using the content management system. Much of this content is created in a Word Processing program such as Microsoft Word. In many cases, the content is not formatted correctly for the web. While the cms does a good job of filtering out the Word Document markup, there are still some charaters that get through the filter, but don’t display properly on the web. These  characters show up as odd symbols such as diamonds and squares. I have created a filter to run the content through before it is displayed, finding the invalid characters and replacing them with html character codes.

 

Due to the restraints of the system I am working in, I decided to go with a vbscript dictionary object to hold an array of characters that were not displaying properly in the browser. I created an api that could be included into any page, and used an algorithm to detect and replace the pesky invalid characters.

‘——————————
‘_____________________________
‘ function to replace extended asci chars with the html equivalent ‘***************************
Function replace_characters(inString)
newstring = inString
dim lamechars
Set lamechars = CreateObject _
(“Scripting.Dictionary”)
lamechars.Add “–”, “–”
lamechars.Add “®”, “®”
lamechars.Add “’”, “’”
lamechars.Add ““”, ““”
lamechars.Add “””, “””
lamechars.Add “—”, “–”
For Each character in lamechars
newstring=Replace(newstring, character, lamechars(character))

Next
Response.Write(newstring)
End Function
‘**************************
‘ end function to replace extended asci chars with the html equivalent ‘—————————

Looking at the PHP Form Post Object

I use php to talk with MySQL db server. It comes in handy for making apps. Here are the code variations for receiving POST variables from a client request and ,for debug, a quick list of the variables, names and values. Using this: print_r($_POST); this gives a breakdown of the array holding the data from the post variables…. Array ( [signindate] => 11/4/2011 [signintime] => 15:33 PM [nameofchild] => dev en [parentsignature] => don e [in] => Sign In ) to access an element of the array I use a couple methods.. to get them one by one  by name so I can put them into the database.. $myformelement=$_POST[‘form element field html id name’];

Now that the records are correctly inserting into database, my next step is to  use some ajax to call the php behind the scenes while leaving my webapp ui view intact.

  • Check if a person is selected
  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a file on the server

Add a Zero (0) in front of numbers below ten (10)

In certain situation I need to add a zero in front of numbers below ten. It could be used for money, .05 and for time :05 and I’m sure there are other situations where this could be useful.

// add zer0 in front of minutes below ten 10
function pad(n) {if (n < 10) return “0” + n; return n;}

// use the pad function
for(var minute=0; minute<50;minute=minute+5){
$(“#minutes”).append(“<option value='”+pad(minute)+”‘>”+pad(minute)+”</option>”);
}

Creating dynamic selects using Javascript and JQuery

I need to have a select form element, with the options generated from dynamic content that could come from a database or an array, with an unknown number of options. Then, I need to create two more selects, with all of the options except the ones selected in the previous select. For example, a user must choose their first, second, and third choices for college.

Lets say we have a list of colleges and their abbreviations:

<input type=”checkbox” name=”scholarshipschools” value=”CWU” title=”Please select a college.” /> Central Washington Univ, Ellensburg <br />
<input type=”checkbox” name=”scholarshipschools” value=”EWU” /> Eastern Washington Univ, Cheney <br />
<input type=”checkbox” name=”scholarshipschools” value=”SVC”  /> Skagit Valley College <br />
<input type=”checkbox” name=”scholarshipschools” value=”ESC” /> The Evergreen State College, Olympia    <br />
<input type=”checkbox” name=”scholarshipschools” value=”UWB” /> Univ of Washington, Bothell <br />
<input type=”checkbox” name=”scholarshipschools” value=”UWS” /> Univ of Washington, Seattle <br />
<input type=”checkbox” name=”scholarshipschools” value=”UWT” /> Univ of Washington, Tacoma <br />
<input type=”checkbox” name=”scholarshipschools” value=”WSU” /> Washington State Univ, Pullman <br />
<input type=”checkbox” name=”scholarshipschools” value=”WWU” /> Western Washington Univ, Bellingham

 

The checkboxes don’t allow the user to choose what ones would be their first, second and third choices. Also, doesn’t let the user know that they are limited to choosing three. I have been asked to redesign this form so that the user has a better interaction with the page.

I don’t want to type the names of the schools and their abbreviations more than once while I develop this, so the first thing I want to try is to put them into an array, then I can use them when, where and in whatever container I wish. (like changing from checkboxes to selects).

 

var thecollegeabbr = [“CWU”,”EWU”, “SVC”, “ESC”, “UWB”, “UWS”, “UWT”, “WSU”, “WWU”];

var thecolleges = [“Central Washington Univ, Ellensburg”, “Eastern Washington Univ, Cheney”, “Skagit Valley College”, “The Evergreen State College, Olympia”, “Univ of Washington, Bothell”, “Univ of Washington, Seattle”, “Univ of Washington, Tacoma”, “Washington State Univ, Pullman”, “Western Washington Univ, Bellingham”];

I would like for the college name to have its abbreviation attached to it, rather than have them in two separate arrays. Using the information from my previous post on JavaScript Array Best Practices, I see that I could streamline this a little, and make a more efficient 2-dimensional array. I will use a for-if loop to push the abbreviation and title into a two dimensional array.

var thecollegechoices=[];
// combine the abbreviation and the title into a two dimensional array…
for(i=0;i<thecollegeabbr.length;i++){thecollegechoices.push([thecollegeabbr[i], thecolleges[i]]); }

Now that I have an array of data to populate the selects, I will create an algorithm to  put the data into the “First Choice” selector:
// now put the data into a select element
for(i=0;i<thecollegechoices.length;i++){
$(“#firstcollegechoice”).append(“<option value='”+ thecollegechoices[i][0] +”‘>”+ thecollegechoices[i][1] +”</option>”);
} // end for loop to put the data into a select element

screen shot of dynamic selectThe results are very effective, as I now have a select that was dynamically populated using the array of data that I was provided. The next step is where this really starts to get fun. Now I need to create a “Second Choice” selector using all of the choices from the first one, except for the one that was chosen by the user in the “First Choice” selector. This will need an algorithm that is a bit more complex, and will be triggered by the event of the user choosing the first choice.

From my previous article about using JQuery to handle events, I know that I can access the onchange event handler and give it a method that will run my function when the user changes the value of the select. I will build the algorithm into this method as so:

  • Get the value of the college that the user has chosen.
  • Rebuild my array of “thecollegechoices”, eliminating the option that was previously chosen.
  • Populate the options of the “Second Choice” selector using the new data that has been  put into thecollegechoices array.

Here is a snippet of what this looks like now…

$( ‘#firstcollegechoice’ ).on(“change”, function(){
var thecollegechoices=[];
for(i=0;i<thecollegeabbr.length;i++){
// check here to see if the choice is used in the first select.
if(thecollegeabbr[i]!=$(“#firstcollegechoice :selected”).val())                                {thecollegechoices.push([thecollegeabbr[i], thecolleges[i]]);}
}

for(i=0;i<thecollegechoices.length;i++){$(“#secondcollegechoice”).append(“<option value='”+ thecollegechoices[i][0] +”‘>”+ thecollegechoices[i][1] +”</option>”);}

}); // end first choice change functions

 

Dang, this is lookin good. I now have a second choice selector with all the options except for the one that was chosen by the user in the first selector.

It seems like an easy path to our goal, a “Third Choice” selector with all of the options except what was chosen in one and two. Then we are left with some ui clean up to ensure a good user experience. I like to use responsive disclosure to guide the user through a form whenever possible. For this instance, I will disable the second and third choice drop-downs until they are needed, so the user will easily see what they need to do.

———————————– here is the dev code ———————————–

<select name=”scholarshipschools” id=”firstcollegechoice” ><option value=””>First Choice</option></select>
<select name=”scholarshipschools” id=”secondcollegechoice” disabled=”disabled”><option value=””>Second Choice</option></select>
<select name=”scholarshipschools” id=”thirdcollegechoice” disabled=”disabled”><option value=””>Third Choice</option></select>

<script>
// make an array to hold the college choices.
var thecollegeabbr = [“CWU”,”EWU”, “SVC”, “ESC”, “UWB”, “UWS”, “UWT”, “WSU”, “WWU”];
var thecolleges = [“Central Washington Univ, Ellensburg”, “Eastern Washington Univ, Cheney”, “Skagit Valley College”, “The Evergreen State College, Olympia”, “Univ of Washington, Bothell”, “Univ of Washington, Seattle”, “Univ of Washington, Tacoma”, “Washington State Univ, Pullman”, “Western Washington Univ, Bellingham”];
var thecollegechoices=[];

// combine the abbreviation and the title into a two dimensional array…
for(i=0;i<thecollegeabbr.length;i++){thecollegechoices.push([thecollegeabbr[i], thecolleges[i]]); }

// now put the data into a select element
for(i=0;i<thecollegechoices.length;i++){$(“#firstcollegechoice”).append(“<option value='”+ thecollegechoices[i][0] +”‘>”+ thecollegechoices[i][1] +”</option>”);}

$( ‘#firstcollegechoice’ ).on(“change”, function(){
//$(“#debugzone”).html($(this).val() + ” chosen now build the second select<br />”);
$(“#secondcollegechoice”).html(“<option value=”>Second Choice</option>”).removeAttr(“disabled”);$(“#thirdcollegechoice”).html(“<option value=”>Third Choice</option>”).attr(“disabled”, “disabled”);
var thecollegechoices=[];
for(i=0;i<thecollegeabbr.length;i++){
// check here to see if the choice is used in the first select.
if(thecollegeabbr[i]!=$(“#firstcollegechoice :selected”).val()){thecollegechoices.push([thecollegeabbr[i], thecolleges[i]]);}
}

for(i=0;i<thecollegechoices.length;i++){$(“#secondcollegechoice”).append(“<option value='”+ thecollegechoices[i][0] +”‘>”+ thecollegechoices[i][1] +”</option>”);}

});

$( ‘#secondcollegechoice’ ).on(“change”, function(){
//$(“#debugzone”).html($(this).val() + ” chosen now build the third select<br />”);
$(“#thirdcollegechoice”).html(“<option value=”>Third Choice</option>”).removeAttr(“disabled”);
var thecollegechoices=[];
for(i=0;i<thecollegeabbr.length;i++){
// check here to see if the choice is used in the first select.
if(thecollegeabbr[i]!=$(“#firstcollegechoice :selected”).val() && thecollegeabbr[i]!=$(“#secondcollegechoice :selected”).val()){
thecollegechoices.push([thecollegeabbr[i], thecolleges[i]]);
}
}

for(i=0;i<thecollegechoices.length;i++){$(“#thirdcollegechoice”).append(“<option value='”+ thecollegechoices[i][0] +”‘>”+ thecollegechoices[i][1] +”</option>”);}

});

</script>
<!– end new content dev area –>

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]