Javascript syntax and examples

Placement of Javascript within a webpage


<HTML>
<HEAD>
<TITLE>Title</TITLE>
<SCRIPT LANGUAGE=JAVASCRIPT TYPE ="TEXT/JAVASCRIPT">
<!--
Javascript Statements and Functions
-->
<SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>


Referencing a Javascript file within a webpage


<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.


Triggering Javascript to run using a Hyperlink

<A HREF="javascript:Function name to run()" >Instruction to User. </A>


Using the on change event

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

24 Row x 80 Column
Screen Position Calculator

_ X _

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)" >


Comments

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
*/


Declaring Variables

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";

Arrays

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

Or

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.
}


Variable is less than criteria
if(input < 20 ){
Statements to process
}
Variable is equal to criteria
if(input == 20 ){
Statements to process
}
Variable is less than or equal to criteria
if(input <= 20 ){
Statements to process
}
Variable is greater than or equal to criteria
if(input >= 20 ){
Statements to process
}
Variable is not equal to criteria
if(input != 20 ){
Statements to process
}
Both criteria must be met to be true
if(firstvar != 20 && secondvar == 2 ){
Statements to process
}
One or both criteria must be met to be true
if(firstvar != 20 || secondvar == 2 ){
Statements to process
}
Variable is not a number
if(isNaN(firstvar)) {
Statements to process
}
If then or else
if(input == 20 ){
Statements to process
}
else {
Statements to process
}
Value of the Variable is an empty string
if(input == ""){
Statements to process
}


Switch Conditional Statement

switch ( ExpressionToMatch) {
case "Maryland" :
Statements;
break;
case "Delaware ":
Statements;
break;
case "West Virginia ":
Statements;
break;
case "New York ":
break;
default :
Statements;
}


Loop Statements

for ( var cnt = 0; cnt < 10; cnt++) {
Statements;
}


Do While Loop

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);


While Loop

Will continue to loop while the specified condition is true.

var cnt= 0;
while( cnt < 5) {
cnt ++;
}


For In Loop

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. }


Document Object

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)


Math Functions

parseFloat(string)
Converts a string to a floating point number
parseInt()
Converts a string to an integer.

The Math Object's Properties

.E
Euler's constant
.PI
The value of Pi

The Math Object's Methods

The parameter is a number or a variable with a numeric value

Math.abs(parameter)
Returns the absolute value of the number passed to it.
Math.floor(parameter)
If the parameter provided is an integer, it will return that number otherwise it will round up to the next integer.
Math.round(parameter)
Rounds a number to the nearest integer.
Math.max(First Parameter ,Second Parameter)
Returns the greater of two numbers.
Math.min(First Number ,Second Number)
Returns the least of two numbers.
Math.pow(parameter,power)
Calculates the parameter to the specified power.
Math.sqrt(parameter)
Calculates and returns the squareroot of the parameter.
Math.cos(parameter)
Calculates and returns the cosine of the parameter.
Math.sin(parameter)
Calculates and returns the sine of the parameter.
Math.tan(parameter)
Calculates and returns the tangent of the parameter.

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.

Rounding Real Numbers with Javascript 1.5 +

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 .


Communicating with the application user

The prompt, alert and confirm functions.

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()

Hosted by www.Geocities.ws

1