Commit 12f02196 by O'Reilly Media, Inc.

Initial commit

parents
9780596004675
\ No newline at end of file
## Example files for the title:
# JavaScript & DHTML Cookbook, by Danny Goodman
[![JavaScript & DHTML Cookbook, by Danny Goodman](http://akamaicovers.oreilly.com/images/9780596004675/cat.gif)](https://www.safaribooksonline.com/library/view/title/0596004672//)
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.
var isMac = (navigator.userAgent.indexOf("Mac") != -1);
var isIEMac = (isMac && navigator.appName == "Microsoft Internet Explorer");
var isSafari = (navigator.userAgent.indexOf("Safari") != -1);
// let page's onload handle first time out for IE/Mac and Safari
function fauxLoad(elemID) {
if (isIEMac || isSafari) {
setTimeout("adjustIFrameSize('" + elemID + "')", 1000);
}
}
// invoked from iframe's onload event handler
function adjustIFrameSize(elemID) {
var myIframe = document.getElementById(elemID);
if (myIframe) {
// Safari needs timeout, so group them all together
setTimeout("finishSizing('" + elemID + "')", 50);
}
}
// size the iframe to its content (browser willing)
function finishSizing(elemID) {
var myIframe = document.getElementById(elemID);
if (myIframe.contentDocument && myIframe.contentDocument.body.offsetHeight) {
// W3C DOM (NN6+/Mozilla/Safari) syntax; Safari needs timeout
myIframe.style.height = myIframe.contentDocument.body.offsetHeight + "px";
} else if (myIframe.Document && myIframe.Document.body.scrollHeight) {
// IE/Windows DOM syntax
myIframe.style.height = myIframe.Document.body.scrollHeight + "px";
} else if (myIframe.document && myIframe.document.body.offsetHeight) {
// IE/Mac DOM syntax -- if only it worked :-(
myIframe.style.height = myIframe.document.body.offsetHeight + "px";
}
}
----------
<body onload = "fauxLoad('myFrame')">
<iframe id="myFrame" frameborder="0" vspace="0" hspace="0" marginwidth="0"
marginheight="0" width="100%" src="http://www.dannyg.com/new.html" scrolling="no"
style="overflow:visible" onload="adjustIFrameSize(this.id)"></iframe>
----------
// validates that the field value string has one or more characters in it
function isNotEmpty(elem) {
var str = elem.value;
if(str == null || str.length == 0) {
alert("Please fill in the required field.")
return false;
} else {
return true;
}
}
// validates that the entry is a positive or negative number
function isNumber(elem) {
var str = elem.value;
var oneDecimal = false;
var oneChar = 0;
// make sure value hasn't cast to a number data type
str = str.toString();
for (var i = 0; i < str.length; i++) {
oneChar = str.charAt(i).charCodeAt(0);
// OK for minus sign as first character
if (oneChar == 45) {
if (i == 0) {
continue;
} else {
alert("Only the first character may be a minus sign.");
return false;
}
}
// OK for one decimal point
if (oneChar == 46) {
if (!oneDecimal) {
oneDecimal = true;
continue;
} else {
alert("Only one decimal is allowed in a number.");
return false;
}
}
// characters outside of 0 through 9 not OK
if (oneChar < 48 || oneChar > 57) {
alert("Enter only numbers into the field.");
return false;
}
}
return true;
}
// validates that the entry is 16 characters long
function isLen16((elem) {
var str = elem.value;
if (str.length != 16) {
alert("Entry does not contain the required 16 characters.");
return false;
} else {
return true;
}
}
// validates that the entry is formatted as an email address
function isEMailAddr(elem) {
var str = elem.value;
str = str.toLowerCase();
if (str.indexOf("@") > 1) {
var addr = str.substring(0, str.indexOf("@"));
var domain = str.substring(str.indexOf("@") + 1, str.length);
// at least one top level domain required
if (domain.indexOf(".") == -1) {
alert("Verify the domain portion of the email address.");
return false;
}
// parse address portion first, character by character
for (var i = 0; i < addr.length; i++) {
oneChar = addr.charAt(i).charCodeAt(0);
// dot or hyphen not allowed in first position; dot in last
if ((i == 0 && (oneChar == 45 || oneChar == 46)) ||
(i == addr.length - 1 && oneChar == 46)) {
alert("Verify the user name portion of the email address.");
return false;
}
// acceptable characters (- . _ 0-9 a-z)
if (oneChar == 45 || oneChar == 46 || oneChar == 95 ||
(oneChar > 47 && oneChar < 58) || (oneChar > 96 && oneChar < 123)) {
continue;
} else {
alert("Verify the user name portion of the email address.");
return false;
}
}
for (i = 0; i < domain.length; i++) {
oneChar = domain.charAt(i).charCodeAt(0);
if ((i == 0 && (oneChar == 45 || oneChar == 46)) ||
((i == domain.length - 1 || i == domain.length - 2) && oneChar == 46)) {
alert("Verify the domain portion of the email address.");
return false;
}
if (oneChar == 45 || oneChar == 46 || oneChar == 95 ||
(oneChar > 47 && oneChar < 58) || (oneChar > 96 && oneChar < 123)) {
continue;
} else {
alert("Verify the domain portion of the email address.");
return false;
}
}
return true;
}
alert("The email address may not be formatted correctly. Please verify.");
return false;
}
var myString = "Every good boy does fine.";
var section = myString.substring(0, 10); // section is now "Every good"
----------
var myString = "Every good boy does fine.";
var section = myString.slice(11, -6); // section is now "boy does"
----------
var myString = "Every good boy does fine.";
var section = myString.substr(6, 4); // section is now "good"
var myString = "New York";
var lcString = myString.toLowerCase();
var ucString = myString.toUpperCase();
----------
myString = myString.toLowerCase();
----------
<input type="text" name="firstName" id="firstName" size="20" maxlength="25"
onchange="this.value = this.value.toUpperCase()" />
function handleClick(evt) {
var evt = (evt) ? evt : ((window.event) ? window.event : null);
if (evt) {
var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if (elem && elem.id.indexOf("menuImg") == 0) {
// process events from elements whose IDs begin with "menuImg"
}
}
}
----------
function countInstances(mainStr, srchStr) {
var count = 0;
var offset = 0;
do {
offset = mainStr.indexOf(srchStr, offset);
count += (offset != -1) ? 1 : 0;
} while (offset++ != -1)
return count
}
var shortStr = "Framistan 2000";
var re = new RegExp(shortStr, "g");
var result = longString.match(re);
if (result) {
alert("Found " + result.length + " instances of the text: " + result[0]);
} else {
alert("Sorry, no matches.");
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd"><!-- Example File From "JavaScript and DHTML Cookbook" Published by O'Reilly & Associates Copyright 2003 Danny Goodman --><html><head><title>Recipe 1.7</title><link rel="stylesheet" id="mainStyle" href="../css/cookbook.css" type="text/css" /><script language="JavaScript" type="text/javascript">function doSR(form) { var searchStr = form.srchText.value; var re = new RegExp(searchStr, "g"); var replaceStr = form.replaceText.value; var div = document.getElementById("boilerplate"); div.firstChild.nodeValue = div.firstChild.nodeValue.replace(re, replaceStr);}</script></head><body><h1>1.7. Searching and Replacing Substrings</h1><hr /><form action="" onsubmit="return false"> Search for: <input type="text" id="srchText" name="srchText" size="30" value="\(ph\)" /><br /> Replace with: <input type="text" id="replaceText" name="replaceText" size="30" value="PLACEHOLDER REPLACEMENT" /><br /><div class="buttons"><input type="reset" value="Reset Form" />&nbsp;&nbsp;<input type="button" value="Search and Replace"onclick="doSR(this.form)" /></div></form><h2>Boilerplate Text</h2><p id="boilerplate">Lorem ipsum dolor sit (ph) amet, consectetaur adipisicing elit, sed (ph) do eiusmod (ph) tempor incididunt ut labore et dolore magna aliqua. Ut enim adminim veniam, quis (ph) nostrud exercitation ullamco (ph) laboris nisi ut aliquip ex ea commodo consequat.</p></body></html>
\ No newline at end of file
/* cookies.js *//* Example File From "JavaScript and DHTML Cookbook" Published by O'Reilly & Associates Copyright 2003 Danny Goodman */ // utility function to retrieve a future expiration date in proper format; // pass three integer parameters for the number of days, hours, // and minutes from now you want the cookie to expire; all three // parameters required, so use zeros where appropriate function getExpDate(days, hours, minutes) { var expDate = new Date(); if (typeof days == "number" && typeof hours == "number" && typeof hours == "number") { expDate.setDate(expDate.getDate() + parseInt(days)); expDate.setHours(expDate.getHours() + parseInt(hours)); expDate.setMinutes(expDate.getMinutes() + parseInt(minutes)); return expDate.toGMTString(); } } // utility function called by getCookie() function getCookieVal(offset) { var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) { endstr = document.cookie.length; } return unescape(document.cookie.substring(offset, endstr)); } // primary function to retrieve cookie by name function getCookie(name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) { return getCookieVal(j); } i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; } // store cookie value with optional details as needed function setCookie(name, value, expires, path, domain, secure) { document.cookie = name + "=" + escape (value) + ((expires) ? "; expires=" + expires : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); } // remove the cookie by setting ancient expiration date function deleteCookie(name,path,domain) { if (getCookie(name)) { document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; } }
\ No newline at end of file
/**************************************************** base64.js --------- A JavaScript library for base64 encoding and decoding by Danny Goodman (http://www.dannyg.com). Described in "JavaScript and DHTML Cookbook" published by O'Reilly & Associates. Copyright 2003. [Inspired by many examples in many programming languages, but predominantly by Java routines seen in online course notes by Hamish Taylor at http://www.cee.hw.ac.uk/courses/2nq3/4/ The binary data manipulations were very helpful.] This library is self-initializing when included in an HTML page and loaded in a JavaScript-enabled browser. Browser compatibility has been tested back to Netscape 4 and Internet Explorer 5 (Windows and Mac). Two "public" functions accept one string argument (the string to convert) and return a string (the converted output). Because this library is designed only for client-side encoding and decoding (i.e., no encoded data is intended for transmission to a server), the encoding routines here ignore the 76-character line limit for MIME transmission. See details of encoding scheme in RFC2045: http://www.ietf.org/rfc/rfc2045.txt These routines are being used to encode/decode html element attribute values, which may not contain an equals (=) symbol. Thus, we do not allow padding of uneven block lengths. To encode a string, invoke: var encodedString = base64Encode("stringToEncode"); To decode a string, invoke: var plainString = base64Decode("encodedString"); Release History --------------- v.1.00 07Apr2003 First release ****************************************************/// Global lookup arrays for base64 conversions var enc64List, dec64List; // Load the lookup arrays once function initBase64() { enc64List = new Array(); dec64List = new Array(); var i; for (i = 0; i < 26; i++) { enc64List[enc64List.length] = String.fromCharCode(65 + i); } for (i = 0; i < 26; i++) { enc64List[enc64List.length] = String.fromCharCode(97 + i); } for (i = 0; i < 10; i++) { enc64List[enc64List.length] = String.fromCharCode(48 + i); } enc64List[enc64List.length] = "+"; enc64List[enc64List.length] = "/"; for (i = 0; i < 128; i++) { dec64List[dec64List.length] = -1; } for (i = 0; i < 64; i++) { dec64List[enc64List[i].charCodeAt(0)] = i; } } function base64Encode(str) { var c, d, e, end = 0; var u, v, w, x; var ptr = -1; var input = str.split(""); var output = ""; while(end == 0) { c = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : ((end = 1) ? 0 : 0); d = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : ((end += 1) ? 0 : 0); e = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : ((end += 1) ? 0 : 0); u = enc64List[c >> 2]; v = enc64List[(0x00000003 & c) << 4 | d >> 4]; w = enc64List[(0x0000000F & d) << 2 | e >> 6]; x = enc64List[e & 0x0000003F]; // handle padding to even out unevenly divisible string lengths if (end >= 1) {x = "=";} if (end == 2) {w = "=";} if (end < 3) {output += u + v + w + x;} } // format for 76-character line lengths per RFC var formattedOutput = ""; var lineLength = 76; while (output.length > lineLength) { formattedOutput += output.substring(0, lineLength) + "\n"; output = output.substring(lineLength); } formattedOutput += output; return formattedOutput; } function base64Decode(str) { var c=0, d=0, e=0, f=0, i=0, n=0; var input = str.split(""); var output = ""; var ptr = 0; do { f = input[ptr++].charCodeAt(0); i = dec64List[f]; if ( f >= 0 && f < 128 && i != -1 ) { if ( n % 4 == 0 ) { c = i << 2; } else if ( n % 4 == 1 ) { c = c | ( i >> 4 ); d = ( i & 0x0000000F ) << 4; } else if ( n % 4 == 2 ) { d = d | ( i >> 2 ); e = ( i & 0x00000003 ) << 6; } else { e = e | i; } n++; if ( n % 4 == 0 ) { output += String.fromCharCode(c) + String.fromCharCode(d) + String.fromCharCode(e); } } } while (typeof input[ptr] != "undefined"); output += (n % 4 == 3) ? String.fromCharCode(c) + String.fromCharCode(d) : ((n % 4 == 2) ? String.fromCharCode(c) : ""); return output; } // Self-initialize the global variables initBase64();
\ No newline at end of file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd"><!-- Example File From "JavaScript and DHTML Cookbook" Published by O'Reilly & Associates Copyright 2003 Danny Goodman --><html><head><title>Recipe 1.12</title><link rel="stylesheet" id="mainStyle" href="../css/cookbook.css" type="text/css" /><script type="text/javascript" src="base64.js"></script><script language="JavaScript" type="text/javascript">function doEncode(btn) { var form = btn.form; form.input2.value = "" form.output.value = "" form.input2.value = base64Encode(form.input1.value);} function doRoundTrip(btn) { doEncode(btn); doDecode(btn);} function doDecode(btn) { var form = btn.form; form.output.value = base64Decode(form.input2.value);}</script></head><body><h1>1.12. base64.js Laboratory</h1><hr /><form onsubmit="return false"><p>Enter a "plain" string to be encoded:</p><textarea cols="80" rows="20" id="input1"></textarea><input type="button" value="Encode" onclick="doEncode(this)"><input type="button" value="Round Trip" onclick="doRoundTrip(this)"></p> <p>Enter a base64-encoded string to be decoded:</p><textarea cols="80" rows="20" id="input2"></textarea><input type="button" value="Decode" onclick="doDecode(this)"></p> <p>Decoded output:</p><textarea cols="80" rows="20" id="output"></textarea></p> </form></body></html>
\ No newline at end of file
html {background-color:#cccccc}body {background-color:#eeeeee; font-family:Tahoma,Arial,Helvetica,sans-serif; font-size:12px; margin-left:15%; margin-right:15%; border:3px groove darkred; padding:15px}h1 {text-align:right; font-size:1.5em; font-weight:bold}h2 {text-align:left; font-size:1.1em; font-weight:bold; text-decoration:underline}.buttons {margin-top:10px}
\ No newline at end of file
var val1 = parseFloat(document.myForm.firstNum.value);
var val2 = parseFloat(document.myForm.secondNum.value);
var result = val1 + val2;
document.myForm.sum.value = result;
----------
var mainVer = parseInt(navigator.appVersion, 10);
\ No newline at end of file
if (typeof someVal == "number") {
// OK, operate on the value numerically
}
----------
var myVal = parseInt(document.myForm.myAge.value);
if (isNaN(myVal)) {
alert("Please check the Age text box entry.");
} else {
// OK, operate on the value numerically
}
document.myForm.total.value = someNumber.toFixed(2);
----------
document.myForm.rate.value = someNumber.toPrecision(5);
----------
function formatNumber (num, decplaces) {
// convert in case it arrives as a string value
num = parseFloat(num);
// make sure it passes conversion
if (!isNaN(num)) {
// multiply value by 10 to the decplaces power;
// round the result to the nearest integer;
// convert the result to a string
var str = "" + Math.round (eval(num) * Math.pow(10,decplaces));
// exponent means value is too big or small for this routine
if (str.indexOf("e") != -1) {
return "Out of Range";
}
// if needed for small values, pad zeros
// to the left of the number
while (str.length <= decplaces) {
str = "0" + str;
}
// calculate decimal point position
var decpoint = str.length - decplaces;
// assemble final result from: (a) the string up to the position of
// the decimal point; (b) the decimal point; and (c) the balance
// of the string. Return finished product.
return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
} else {
return "NaN";
}
}
document.myForm.total.value = formatNumber(someNumber, 2);
----------
function formatCommas(numString) {
var re = /(-?\d+)(\d{3})/;
while (re.test(numString)) {
numString = numString.replace(re, "$1,$2");
}
return numString;
}
function formatNumber (num, decplaces) {
// convert in case it arrives as a string value
num = parseFloat(num);
// make sure it passes conversion
if (!isNaN(num)) {
// multiply value by 10 to the decplaces power;
// round the result to the nearest integer;
// convert the result to a string
var str = "" + Math.round (eval(num) * Math.pow(10,decplaces));
// exponent means value is too big or small for this routine
if (str.indexOf("e") != -1) {
return "Out of Range";
}
// if needed for small values, pad zeros
// to the left of the number
while (str.length <= decplaces) {
str = "0" + str;
}
// calculate decimal point position
var decpoint = str.length - decplaces;
// assemble final result from: (a) the string up to the position of
// the decimal point; (b) the decimal point; and (c) the balance
// of the string. Return finished product.
return formatCommas(str.substring(0,decpoint)) + "." + str.substring(decpoint,str.length);
} else {
return "NaN";
}
}
----------
function stripCommas(numString) {
var re = /,/g;
return numString.replace(re,"");
}
function dec2Hex(dec) {
dec = parseInt(dec, 10);
if (!isNaN(dec)) {
hexChars = "0123456789ABCDEF";
if (dec > 255) {
return "Out of Range";
}
var i = dec % 16;
var j = (dec - i) / 16;
result = "0x";
result += hexChars.charAt(j) + hexChars.charAt(i);
return result;
} else {
return NaN;
}
}
function daysBetween(date1, date2) {
var DSTAdjust = 0;
// constants used for our calculations below
oneMinute = 1000 * 60;
var oneDay = oneMinute * 60 * 24;
// equalize times in case date objects have them
date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
date2.setHours(0);
date2.setMinutes(0);
date2.setSeconds(0);
// take care of spans across Daylight Saving Time changes
if (date2 > date1) {
DSTAdjust =
(date2.getTimezoneOffset() - date1.getTimezoneOffset()) * oneMinute;
} else {
DSTAdjust =
(date1.getTimezoneOffset() - date2.getTimezoneOffset()) * oneMinute;
}
var diff = Math.abs(date2.getTime() - date1.getTime()) - DSTAdjust;
return Math.ceil(diff/oneDay);
}
var projectLength = 0;
// validate form entries with checkDate() function from Recipe 2.12
var startField = document.entryForm.startDate;
var endField = document.entryForm.endDate;
if (checkDate(startField) && checkDate(endField)) {
var startDate = new Date(startField.value);
var endDate = new Date(endField.value);
projectLength = daysBetween(startDate, endDate);
}
if (projectLength > 0) {
alert("You\'ve specified " + projectLength + " days for this project.");
}
function checkDate(fld) {
var mo, day, yr;
var entry = fld.value;
var re = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
if (re.test(entry)) {
var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
var delim1 = entry.indexOf(delimChar);
var delim2 = entry.lastIndexOf(delimChar);
mo = parseInt(entry.substring(0, delim1), 10);
day = parseInt(entry.substring(delim1+1, delim2), 10);
yr = parseInt(entry.substring(delim2+1), 10);
var testDate = new Date(yr, mo-1, day);
alert(testDate)
if (testDate.getDate() == day) {
if (testDate.getMonth() + 1 == mo) {
if (testDate.getFullYear() == yr) {
return true;
} else {
alert("There is a problem with the year entry.");
}
} else {
alert("There is a problem with the month entry.");
}
} else {
alert("There is a problem with the date entry.");
}
} else {
alert("Incorrect date format. Enter as mm/dd/yyyy.");
}
return false;
}
function validateDate(fld) {
if (!checkDate(fld)) {
// focus if validation fails
fld.focus();
fld.select();
}
}
----------
function checkDate(fld) {
var mo, day, yr;
var entry = fld.value;
var reLong = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
var reShort = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{2}\b/;
var valid = (reLong.test(entry)) || (reShort.test(entry));
if (valid) {
var delimChar = (entry.indexOf("/") != -1) ? "/" : "-";
var delim1 = entry.indexOf(delimChar);
var delim2 = entry.lastIndexOf(delimChar);
mo = parseInt(entry.substring(0, delim1), 10);
day = parseInt(entry.substring(delim1+1, delim2), 10);
yr = parseInt(entry.substring(delim2+1), 10);
// handle two-digit year
if (yr < 100) {
var today = new Date();
// get current century floor (e.g., 2000)
var currCent = parseInt(today.getFullYear() / 100) * 100;
// two digits up to this year + 15 expands to current century
var threshold = (today.getFullYear() + 15) - currCent;
if (yr > threshold) {
yr += currCent - 100;
} else {
yr += currCent;
}
}
var testDate = new Date(yr, mo-1, day);
if (testDate.getDate() == day) {
if (testDate.getMonth() + 1 == mo) {
if (testDate.getFullYear() == yr) {
// fill field with database-friendly format
fld.value = mo + "/" + day + "/" + yr;
return true;
} else {
alert("There is a problem with the year entry.");
}
} else {
alert("There is a problem with the month entry.");
}
} else {
alert("There is a problem with the date entry.");
}
} else {
alert("Incorrect date format. Enter as mm/dd/yyyy.");
}
return false;
}
var amounts = "30.25,120.00,45.09,200.10";
var amtArray = amounts.split(/\.\d{2},?/);
\ No newline at end of file
var myArray = ["Alice", "Fred", "Jean", "Steve"];
for (var i = 0; i < myArray.length ; i++) {
alert("Item " + i + " is:" + myArray[i] + ".");
}
----------
var myArray = ["Alice", "Fred", "Jean", "Steve"];
for (var i = myArray.length 1; i >= 0 ; i--) {
alert("Item " + i + " is:" + myArray[i] + ".");
}
----------
var nameList = ["Alice", "Fred", "Jean", "Steve"];
var ageList = [23, 32, 28, 24];
function ageLookup(name) {
for (var i = 0; i < nameList.length ; i++) {
if (nameList[i] == name) {
return ageList[i];
}
return "Could not find " + name + ".";
}
----------
function clearTextBoxes() {
var allInputs = document.getElementsByTagName("input");
for (var i = 0; i < allInputs.length; i++) {
if (allInputs[i].type == "text") {
allInputs[i].value = "";
}
}
}
----------
var salesArray = [[2300, 3105, 2909, 4800],
[1800, 1940, 2470, 4350],
[900, 1200, 1923, 3810]];
var total = 0;
for (var i = 0; i < salesArray.length; i++) {
for (var j = 0; j < salesArray[i].length; j++) {
total += salesArray[i][j];
}
}
function coworker(name, age) {
this.name = name;
this.age = age;
}
var emp1 = new coworker("Alice", 23);
var emp2 = new coworker("Fred", 32);
----------
var emp1 = {name:"Alice", age:23};
var emp2 = {name:"Fred", age:32};
----------
function showAll() {
alert("Employee " + this.name + " is " + this.age + " years old.");
}
function coworker(name, age) {
this.name = name;
this.age = age;
this.show = showAll;
}
var emp1 = {name:"Alice", age:23, show:showAll};
var emp2 = {name:"Fred", age:32, show:showAll};
emp1.show();
----------
function coworker(name, age) {
this.name = name;
this.age = age || 0;
this.show = showAll;
}