Wednesday, April 23, 2008

JavaScript HashMap

Okay, this is not new nor exciting but I was looking to create something like a Java HashMap or a C# Dictionary object in JavaScript. What I did find was that you can use a JavaScript Array to function as a hashmap or dictionary object. I would then use it to iterate through to do some quick client-side validation for a web page. Here is the code:

function formFieldArray(){
var myArray = new Array(10);
myArray['myname'] = "Name";
myArray['myaddress'] = "Address";
myArray['mycity'] = "City";
myArray['mystate'] = "State";
myArray['myzip'] = "Zip Code";
myArray['myPhone'] = "Phone Number";
myArray['myEmail'] = "Email Address";
myArray['cardname'] = "Name as it appears on the Card";
myArray['cardNumber'] = "Card Number";
myArray['expDate'] = "Expiration Date";
myArray['cardCode'] = "Card Security Code";

return myArray;
}

function validateForm(){
var theFormFieldArray = formFieldArray();

//iterate thru array and clear values
for (key in theFormFieldArray) {
if(eval('document.myForm.' + key + '.value.length == 0')){
alert('Please enter the value for the ' + theFormFieldArray[key] + ' field.');
eval('document.myForm.' + key + '.focus()');
return false;
}
}

document.myForm.action = "yourNextPage.php";
document.myForm.submit();
}