<HTML>
<HEAD>
<TITLE>Title</TITLE>
<SCRIPT LANGUAGE=JAVASCRIPT TYPE ="TEXT/JAVASCRIPT">
<!--
Javascript Statements and Functions
-->
<SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>Title</TITLE>
<SCRIPT SRC="filename.js" LANGUAGE=JAVASCRIPT TYPE ="TEXT/JAVASCRIPT"> </SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Using a js file allows you to call functions and pass values to them just as though the code were written in the webpage. Additionally the code can be used by many pages.
<A HREF="javascript:Function name to run()" >Instruction to User. </A>
The example below is a calculator that is used to calculate the cursor position in a terminal emulator . When the row or column value in the form is changed, the function IdentifyScrnLoc is triggered and recalculates the screen position
The function call delivers two values to the function. The row number and the column number.
<INPUT TYPE = "text" ID = "lblScrnRow" NAME = "row" defaultValue = " 1 " SIZE = 3 MAXLENGTH = 2
OnChange = " IdentifyScrnLoc(row,col)" >
_ X _ <INPUT TYPE = "text" ID = "lblScrnCol" NAME = "col" defaultValue = " 1 " SIZE = 3
MAXLENGTH = 2 OnChange = "IdentifyScrnLoc(row,col)" >
Commenting code is important to any computer program. Additionally it is useful sometimes to comment sections of code when debugging a script in order to isolate an error.
// Single line comments of presented in this way with two forward slashes before the statement.
/*Multiline comments or sections of text are proceded by a foward slash and asterisk.
They are closed with an asterisk and forward slash
*/
A global variable must be declared outside of all functions on the page. Variables declared within a function are local to that function only. Their values may be passed to other functions as parameters in the function call.
var variableA = 10;
var variableB = "Hello";
var names = new Array();
names[0] = "Armstrong, Peter" ;
names[1]= "Smith, Alan" ;
names[2]= "Jones, Bill" ;
alert(names.length);
// Will generate an alert box with the number three which is the number of elements in the array
var names =new Array("Armstrong, Peter",Smith, Alan","Jones, Bill");
alert(names.length);
// Will generate an alert box with the number three which is the number of elements in the array
Arrays start numbering at 0.
// Object constructor
//Firstline is an array of property names, Anotherline is an array of values for each property
function recordconstruc(Firstline,Anotherline) {
var fieldnames = new Array();
var eachrecord = new Array();
fieldnames = Firstline.split("~") ;
eachrecord = Anotherline.split("~") ;
var cnt = 0;
for(var i = 0;i < fieldnames.length; i++) {
var fieldvalue = fieldnames[i];
this[fieldvalue] = eachrecord[i] ;
}
} // end of function recordconstruct
The javascript code used by this form is listed below
function supplyno(rawno,rounddigits)
{
// Function purpose: supply floating point decimal number and the number of digits to round down to.
//Values are passed on by form 'rndfunction()
//Call rounding function rndresult()
rawresult = rawno.value;
rnddigits= rounddigits.value;
rnddigits= Math.floor(rnddigits);// Make sure that rounding digit is an integer.
realresult = rndresult(rawresult,rnddigits);
// Write result to textbox(result) in the form (rndfunction)
document.rndfunction.result.value = realresult;
}
// order of arguements in function declaration must be the same as the function call.
// in supplyno() - realresult = rndresult(rawresult,rnddigits);
// values are passed based on their order.
//Differences in variable names between functions do not matter because they are local to that function only.
function rndresult(rawresult,rnddigits)
{
//round results and return value
var realresult = rawresult;
var decimalpl = rnddigits;
//take rounding digits and make decimalpl = 10 to the (rounding digits) power
var decimalpl = (Math.pow(10,decimalpl));
// Math.round will only round to nearest integer multiply by 10 to the number of decimal places.
//Round the result and divide by 10 to the number of decimal places.
realresult = (Math.round(realresult *decimalpl))/decimalpl;
var roundedresult = parseFloat(realresult); // make sure number is delivered back to multiply()
return(roundedresult)// return rounded number to calling function.
}
switch ( ExpressionToMatch) {
case "Maryland" :
Statements;
break;
case "Delaware ":
Statements;
break;
case "West Virginia ":
Statements;
break;
case "New York ":
break;
default :
Statements;
}
for ( var cnt = 0; cnt < 10; cnt++) {
Statements;
}
Will continue to loop while the specified condition is true. The condition is evaluated at the bottom of the loop
do {
i = i +1
Statements;
} while ( i < 5);
Will continue to loop while the specified condition is true.
var cnt= 0;
while( cnt < 5) {
cnt ++;
}
The for in loop will cycle through the properties of standard and custom objects.
for (var objectproperty in objectpropertyArray) {
javascript statements
}
The code belows would be contained within a a function and will list all the properties associated with the document object (the webpage)
var wholelist= "" ;//empty quotes
for (var i in document) {
wholelist= wholelist+ "document."+ i + "\t" + document[i] +"\n" ;
}
document.displaytxt.result.value =wholelist;
// displaytext is the form name on the page and result is a textarea to print the results in.
}
To code a backslash within a javascript statement such as in </H1> , proceed it with a front slash as in the example below.
printWindow.document.write('<\/H1>');
Adding a newline(' \n' )will make the HTML more readable
printWindow.document.write('\n') ;
var stats = 'toolbar=no,location=no,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes';
printWindow = window.open("","printwin",stats);
printWindow.document.write('<HTML>');
printWindow.document.write('\n');
printWindow.document.write('<HEAD>');
printWindow.document.write('\n');
printWindow.document.write('<TITLE>Display Table<\/TITLE>' );
printWindow.document.write('<STYLE>' );
printWindow.document.write('\n');
printWindow.document.write('TH {font: bold 12pt "Arial";color:navy} ');
printWindow.document.write('\n');
printWindow.document.write('TD {font: bold 10pt "Arial";color:blue} ');
printWindow.document.write('\n');
printWindow.document.write('<\/STYLE> <\/HEAD>');
printWindow.document.write('<BODY>');
printWindow.document.write('<\/BODY> <\/HTML>');
printWindow.document.close(); //close input to allow Printing of this window text rather than that of the parent window.
}// End of function printresults(title,records)
The parameter is a number or a variable with a numeric value
function rndresult(rawresult,rnddigits)
{
//Function to round numbers to a specified number of decimal places.
//round results and return value
var realresult = rawresult;
var decimalpl = rnddigits;
//take rounding digits and make decimalpl = 10 to the (rounding digits) power
var decimalpl = (Math.pow(10,decimalpl));
// Math.round will only round to nearest integer multiply by 10 to the number of decimal places.
//Round the result and divide by 10 to the number of decimal places.
realresult = (Math.round(realresult * decimalpl))/decimalpl ;
var roundedresult = parseFloat(realresult); // make sure number is delivered back to multiply()
return(roundedresult)// return rounded number.
The toFixed and toPrecision Methods where first introduced in Javascript 1.5. Previous versions of javascript had no math function to round real or floating point numbers only integers, so that it was necessary for programmer had to write code to cope with this situation.
The toFixed method will round a numeric variable to the number of decimal places specified in the parenthesis of the statement.
variable_name.toFixed(number_of_decimal_places)
The toPrecision method on the otherhand will deliver a number which has a total length equal to the number in the parenthesis of the statement.
variable_name.toPrecision(total_length_of_number)
Below is an example showing the difference in the two methods.
var testnumber = 125.02586;
var fixed1 = testnumber.toFixed(4);
var precise1 = testnumber.toPrecision(4);
The result will be fixed1 = 125.0259 and precise1= 125.0 .
Javascript provides three dialog box methods for communicating with the application user.
The prompt() creates a dialog box for the user to enter information.
The confirm() function dialog box has an OK and a Cancel button. Clicking on the ok button returns true.
Clicking on the cancel button returns false.
The alert() function displays a message and an ok button but returns nothing.
Simple demonstration of prompt,alert and confirm.
The javascript code used by this demo is listed below
function communicate()
{
//Demonstrate alert,confirm and prompt functions.
var ask = confirm("Continue?");// returns true or false
alert(ask) ;//Show value of button selected.
// variable = prompt(Message or request,default value or empty quotes for input)
var name = prompt("Please enter your name","");// If cancel is clicked then null will be returned.
if(name == "")
{
alert("Hello No name provided") ;
}
else
{
alert("Hello " + name);
}
}//end of function communicate()