1. Jack Eastwood
Contents
Programming 1.1 Welcome...........................................................................................................1
Programming 1.2 graphical welcome............................................................................................. 6
Programming 1.3 Expressions...................................................................................................... 12
Programming 1.4 Shape area....................................................................................................... 14
Programming 1.5 interest rates................................................................................................... 17
Programming 1.6 Framing a picture............................................................................................. 18
Programming 2.1 getting input from the user............................................................................... 21
Programming 2.2 Numerical input............................................................................................... 24
Programming 2.3 personal details ............................................................................................... 28
2.4 String operations................................................................................................................... 32
2.5 date operations .................................................................................................................... 37
2.6 How old are you?.................................................................................................................. 42
2.7 Event timer........................................................................................................................... 45
3.1 Grading work........................................................................................................................ 47
3.2 Date validation...................................................................................................................... 53
3.3 Coloured event timer............................................................................................................ 59
3.4 Truth tables.......................................................................................................................... 61
Programming 1.1 Welcome
Top tips:
Put semi-colonsatthe endof everything
2 equalssigns=comparison
Variablescanbe overwritten
Watch out for grammar
All variableshave tobe declaredusing“VAR”thenavalue needstobe assignedtothe
variable.
Code iscase sensitive
Orderingof variablesisveryimportant
“//” can be usedtoapplycommentsinyourcode withoutbeingappliedwhenrunningthe
program.
The “prompt” variable displaysawindow thatasksthe userfor an input,inthiscase “Please
enteryourname:”
2. Jack Eastwood
The “alert” variable displaysthe “message”variable onanotherwindow afterthe userhas
put an inputinthe promptwindow.
Wheneversomethingisstoredasa prompt it’sstoredas a string.
== meansequals,!=meansnotequal
parseIntmeansparse integer,meaningthisonlypicksoutanynumerical valuesfromastring
of charactersidentifiedinavariable.
Don’trelyon > or <, use rangeswithdefinedupperandlower limits.
Don’tput a semi-colonatthe endof a for loop.
Var ++ isthe same as var= var + 1
&& meansand, ||meansor
For Weathergraph:
// Ex5-1: Weather Data Graph
var canvas;
canvas = openGraphics();
//You may have to decide where this is best placed
var xOS = 10;
var yOS = 10;
var yAlen = 100;
var xAlen = 150;
//Y axis
canvas.drawLine(xOS, yOS, xOS, yOS+ yAlen);
//X axis
canvas.drawLine(xOS, yOS + yAlen, xOS + xAlen, yOS + yAlen);
canvas.paint();
3. Jack Eastwood
// Ex5-1: Weather Data Graph
var canvas;
canvas = openGraphics();
var xos = 50;
var yos = 50;
var yal = 200;
var xal = 400;
var ylabel = 0;
var ylabelnum = 0;
var xlabel = 0;
var xlabelnum = 0;
//Calculations for points on axis.
//A= xos, yos
//B= xos, yos + yal
//C= xos + xal, yos + yal
canvas.drawLine(xos, yos, xos, yos + yal);
canvas.drawLine(xos, yos + yal, xos + xal, yos + yal);
for(ylabelnum = 0; ylabelnum <= 5; ylabelnum++ )
{
canvas.drawString(ylabel, xos/2, (yos + yal) - ( 40 *
ylabelnum ));
ylabel = ylabel + 40;
}
//You may have to decide where this is best placed
canvas.paint();
Some commentsare actuallyputas commentswithinthe code andhighlightedindarkblue i.e.
//(comment)
4. Jack Eastwood
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
alert( message );
5. Jack Eastwood
var phrase1;
phrase1 = "Hello there ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var phrase3;
phrase3 = " I hope that you enjoy it.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2 + phrase3;
alert( message );
6. Jack Eastwood
Comments:
I changedthe phrase1 message to“hello there”,meaningthatthe window afterItypedmyname in
wouldchange itsfirstsentence promptto“hellothere Jack,”.Phrase3meansthatthere isa new
sentence of the nextwindow,inthiscase to“I hope youenjoyit”,butyouneedto addit to the
variable message.
Programming 1.2 graphical welcome
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.drawString( message, 20, 40 );
canvas.paint();
7. Jack Eastwood
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.drawString( message, 0, 0 );
canvas.paint();
Comments:
8. Jack Eastwood
By changingthe “canvas . drawString( message, (value),(value) )”,itwill change the position of the
outputon the graphical window,byincreasingthe valuesitwill change tobe loweredandmore to
the right.
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.drawString( message, 20, 40);
canvas.drawString( message, 0, 0);
canvas.paint();
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
9. Jack Eastwood
var message;
message = phrase1 + name + phrase2;
canvas.setColor( "red" );
canvas.drawString( message, 20, 40);
canvas.setColor( "blue" );
canvas.drawString( message, 0, 0);
canvas.paint();
Comments:
The “setColor”variable isAmerican.The setColorfunctionchangesanytextunderneath
where itisdeclaredtothe chosencolour. If the userwant to make a differentsentencein
anothercolourthentheywill have todeclare itagainjustabove the string.
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", <br />welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.setColor( "red" );
10. Jack Eastwood
canvas.drawString( message, 20, 40);
canvas.setColor( "blue" );
canvas.drawString( message, 0, 0);
canvas.paint();
Comments:
The <br /> puts the outputon the line underneathafterithasbeendeclared.
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", <br />welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.setFont( "times", "20px", Font.BOLD );
canvas.setColor( "red" );
canvas.drawString( message, 20, 40);
canvas.setColor( "blue" );
canvas.drawString( message, 0, 0);
canvas.paint();
11. Jack Eastwood
Comments:
“canvas.setFont( “times”,“20px”,Font.BOLD);” setsthe fontof the outputto timesnew
roman,make the fontsize to20 pixelsandsetsthe outputto bold.
var canvas;
canvas = openGraphics();
var phrase1;
phrase1 = "Hello, ";
var phrase2;
phrase2 = ", <br />welcome to the Programming module.";
var name;
name = prompt( "Please enter your name:" );
var message;
message = phrase1 + name + phrase2;
canvas.setFont( "comic sans ms", "40px", Font.BOLD_ITALIC );
canvas.setColor( "red" );
canvas.drawString( message, 40, 90);
canvas.setColor( "blue" );
canvas.drawString( message, 0, 0);
canvas.paint();
12. Jack Eastwood
Programming 1.3 Expressions
var a;
a = 0;
var b;
b = 0;
var c;
c = 0;
var result;
result = a + b + c;
alert( result );
var a;
a = 5;
var b;
b = 15;
var c;
c = 7;
var result;
13. Jack Eastwood
result = a + b - c;
alert( result );
var a;
a = 2;
var b;
b = 3;
var c;
c = 4;
var result;
result = a*b + b*c + a*c;
alert( result );
var a;
a = 5;
var b;
b = 4;
var result;
result = (a+b)*(a-b);
alert( result );
14. Jack Eastwood
Comments:
Variablesare assigneddifferentnumericvalues.
“var result”worksout the resultof the valuesgiventoa,band c
* hasto be usedtomultiplyvaluesi.e.“a*b”is“a x b”
“alert( result);”showsthe resultof calculatingthe variablesonawindow
Programming 1.4 Shape area
var canvas;
canvas = openGraphics();
var size;
size = 100;
var area;
area = size * size;
canvas.drawRect( 10, 10, size, size );
// drawRect, short for drawRectangle, requires four values:
// drawRect( x, y, width, height );
// x and y are the coordinates of the top left corner
// width and height are what they say!
// Setting width and height to the same value draws a square
canvas.drawString( "Square of size:", 10, 250 );
canvas.drawString( size, 120, 250 );
canvas.drawString( "Square of area:", 10, 290 );
canvas.drawString( area, 120, 290 );
canvas.paint();
15. Jack Eastwood
Comments
The “can=openGraphics();”opensanew graphical window.
“var size;size 100” setsthe base size of the rectangle to100.
“var area; area size * size “; calculatesthe areaby calculatingsize x size.
“canvas.drawRect( 10, 10 size,size );”the “( 10, 10)” setsthe co-ordinatesof where the
rectangle isbeingplacedinthe window,whilst“(size,size)”setsthe widthandheight
parameters.
var canvas;
canvas = openGraphics();
var size;
size = 200;
var radius;
radius = size/2;
var area;
area = radius*radius*Math.PI;
canvas.drawEllipse( 10, 10, size, size );
//there is a graphics function drawEllipse that requires the same
four values as drawRect but draws an oval shape within the bounds
of the rectangle specified by width and height.
16. Jack Eastwood
//The area of a circle is calculated using the formula: area =
radius2 X pi
//JavaScript already knows the value of pi, it is access using
Math.PI
//A circle of radius 10 has an area of 314.159
canvas.drawString( "Circle of size:", 10, 250 );
canvas.drawString( size, 120, 250 );
canvas.drawString( "Radius of circle:", 10, 290 );
canvas.drawString( radius, 120, 290 );
canvas.drawString( "Area of circle:", 10, 330 );
canvas.drawString( area, 120, 330 );
canvas.paint();
var canvas;
canvas = openGraphics();
var size;
size = 200;
var radius;
radius = size/2;
var area;
area = (radius*radius)*Math.PI;
canvas.setColor( "blue" );
canvas.fillEllipse( 10, 10, size, size );
//there is a graphics function drawEllipse that requires the same
four values as drawRect but draws an oval shape within the bounds
of the rectangle specified by width and height.
//The area of a circle is calculated using the formula: area =
radius2 X pi
//JavaScript already knows the value of pi, it is access using
Math.PI
//A circle of radius 10 has an area of 314.159
canvas.setColor( "black" );
canvas.drawString( "Circle of size:", 10, 250 );
canvas.drawString( size, 120, 250 );
canvas.drawString( "Radius of circle:", 10, 290 );
canvas.drawString( radius, 120, 290 );
canvas.drawString( "Area of circle:", 10, 330 );
canvas.drawString( area, 120, 330 );
canvas.paint();
17. Jack Eastwood
Comments
Canvas.setColor( “blue”);changesthe colourof all objectsinthe window underneathto
blue. Byputtingcanvas.setColor("black");justabove the textthisfillsall objects
underneathtoblackagain.
Programming 1.5 interest rates
var amount;
amount = 250;
var rate;
rate = 10;
var years;
years = 1;
// declare, and initialise, identifiers for rate and time
var interest;
interest = (amount * rate * years)/100;
// input a formula to calculate the interest
//250 x 10=2500 x 1 = 2500/100=25
alert( interest );
18. Jack Eastwood
Programming 1.6 Framing a picture
var canvas;
canvas = openGraphics();
var imageName;
var xPosition;
var yPosition;
var width;
var height;
imageName = "Honeysuckle.jpeg";
xPosition = 80;
yPosition = 100;
//sets the co-ordinates for the position of the image within the
window
width = 200;
height = 150;
//sets the width and height parameters for the image
canvas.setColor ( "white" );
canvas.fillRect ( 30, 30, 300, 300 );
//sets background for the image coloured in white
canvas.drawImage( imageName, xPosition, yPosition, width, height
);
canvas.paint();
19. Jack Eastwood
var canvas;
canvas = openGraphics();
var imageName;
var xPosition;
var yPosition;
var width;
var height;
imageName = "Honeysuckle.jpeg";
xPosition = 80;
yPosition = 100;
//sets the co-ordinates for the position of the image within the
window
width = 200;
height = 150;
//sets the width and height parameters for the image
canvas.setColor ( "white" );
canvas.fillRect ( 30, 30, 300, 300 );
//sets background for the image colored in white
canvas.setColor ( "black" );
canvas.drawRect ( 30, 30, 300, 300 );
//sets a border for the background colored black
canvas.drawImage( imageName, xPosition, yPosition, width, height
);
20. Jack Eastwood
canvas.paint();
var canvas;
canvas = openGraphics();
var imageName;
var xPosition;
var yPosition;
var width;
var height;
imageName = "Honeysuckle.jpeg";
xPosition = 80;
yPosition = 100;
//sets the co-ordinates for the position of the image within the
window
width = 200;
height = 150;
//sets the width and height parameters for the image
canvas.setColor ( "white" );
canvas.fillRect ( 30, 30, 300, 300 );
//sets background for the image colored in white
canvas.setColor ( "black" );
canvas.setStroke( 6 );
//sets width for the width of the frame
canvas.drawRect ( 30, 30, 300, 300 );
//sets a border for the background colored black
21. Jack Eastwood
canvas.drawImage( imageName, xPosition, yPosition, width, height
);
canvas.paint();
Programming 2.1 getting input from the user
// Ex2-1: Based on Ex1-2, Graphical Welcome
// All graphics programs require a canvas on which to draw
var canvas;
canvas = openGraphics();
// comment
var phrase1;
phrase1 = "Hello, ";
// First line that appears in the graphical environment after the
user has inputted their name
// comment
var phrase2;
phrase2 = ",<br />welcome to the Programming module.";
// the "<br>" will place this line underneath the "hello, (name)"
line
// comment
var name;
name = prompt( "Please enter your name:" );
// the first window that appears that prompts the user to input
their name
22. Jack Eastwood
// comment
var message;
message = phrase1 + name + phrase2;
// This will add phrase1 (hello), followed by (name) when the user
inputs their name at the prompt then phrase2 ("welcome to the
programming module") underneath phrase1+name in the graphical
enviroment
// comment
canvas.setFont( "comic sans ms", "15px", Font.BOLD );
// sets the font the graphical environment to comic sans, 15px in
size and sets it to bold letters
// comment
canvas.setColor( "darkred" );
//sets the colour of the output in the graphical environment to
dark red colour
// comment
canvas.drawString( message, 30, 50 );
// sets the co-ordinates of the output either more to the right or
further down (x, y)
// All graphics programs must instruct the browser to
// carry out the commands and render the output
canvas.paint();
23. Jack Eastwood
// Ex2-1: Based on Ex1-2, Graphical Welcome
// All graphics programs require a canvas on which to draw
var canvas;
24. Jack Eastwood
canvas = openGraphics();
// comment
var phrase1;
phrase1 = "Hello, ";
// comment
var phrase2;
phrase2 = ",<br />welcome to the Programming module.";
// comment
var name;
name = prompt( "Please enter your name:" );
var font;
font = prompt( "Enter font style:" );
var color;
color = prompt( "Enter font color:" );
var size;
size = prompt( "Enter font size:" );
// comment
var message;
message = phrase1 + name + phrase2;
// comment
canvas.setFont( font, size, Font.BOLD );
// comment
canvas.setColor( color );
// comment
canvas.drawString( message, 30, 50 );
// All graphics programs must instruct the browser to
// carry out the commands and render the output
canvas.paint();
Programming 2.2 Numerical input
// Ex2-2 : based on Ex1-4
var canvas;
canvas = openGraphics();
var width;
width = prompt( "Enter width of the square" );
width = parseInt(width, 10);
var height;
height = prompt( "Enter height of the square" );
height = parseInt(height, 10);
var size;
size = width*height;
canvas.drawRect( 10, 10, width, height );
// drawRect, short for drawRectangle, requires four values:
// drawRect( x, y, width, height );
25. Jack Eastwood
// x and y are the coordinates of the top left corner
// width and height are what they say!
// Setting width and height to the same value draws a square
canvas.drawRect( 10, 10, width, height );
canvas.drawString( "Area of rectangle:", 10, 250 );
canvas.drawString( size, 10, 270 );
canvas.drawString( "Width of rectangle:", 10, 290 );
canvas.drawString( width, 10, 310 );
canvas.drawString( "height of rectangle:", 10, 330 );
canvas.drawString( height, 10, 350 );
canvas.paint();
26. Jack Eastwood
// Ex2-2 : based on Ex1-4
var canvas;
canvas = openGraphics();
var x = parseInt(prompt( "Enter x co-ordinate for the circle:" ),
10);
var y = parseInt(prompt( "Enter y co-ordinate for the circle" ),
10);
var radius = parseInt(prompt( "Enter radius for the circle" ),
10);
var diameter;
diameter = radius*2;
var area;
area = (radius*radius)*Math.PI;
canvas.drawEllipse( x, y, diameter, diameter );
// drawEllipse, short for drawRectangle, requires four values:
// drawEllipse( x, y, diameter, diameter );
// x and y are the coordinates of the top left corner
// diameter and diameter are needed to draw the circle
// radius of a circle is half of the diameter
// to work out the radius of a circle it is radius x radius x pi
// Math.PI is short for pi (3.1415)
canvas.drawString( "Area of circle:", 10, 250 );
canvas.drawString( area, 10, 270 );
27. Jack Eastwood
canvas.drawString( "Radius of circle:", 10, 290 );
canvas.drawString( radius, 10, 310 );
canvas.drawString( "Diameter of circle:", 10, 330 );
canvas.drawString( diameter, 10, 350 );
canvas.paint();
28. Jack Eastwood
Programming 2.3 personal details
Comments
Forgotto start string witha “.
// Ex 2-3: Personal Details
var canvas;
canvas = openGraphics();
var name;
29. Jack Eastwood
name = prompt( "Please enter your name:" );
var mobile;
mobile = prompt( "Please enter your mobile number: ");
var email;
email = prompt( "Please enter your email address: ");
var dobDay;
dobDay = prompt( "Please enter your birth day: ");
dobDay = parseInt(dobDay, 10);
var dobMonth;
dobMonth = prompt( "Please enter your birth month: ");
dobMonth = parseInt(dobMonth, 10);
var dobYear;
dobYear = prompt( "Please enter your birth year: ");
dobYear = parseInt(dobYear, 10);
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
canvas.setColor( "purple" );
canvas.fillRect(5, 5, 500 ,250);
canvas.setFont( "Arial" , "20px" );
canvas.setColor( "orange" );
canvas.setStroke( 5 );
canvas.drawRect(5, 5, 500, 250);
canvas.setColor( "pink" );
canvas.drawString( "Name: " + name, 10, 10);
canvas.drawString( "Mobile: " + mobile, 10, 50);
canvas.drawString( "Email: " + email, 10, 90);
canvas.drawString( "Date of birth: " + dobDay + "/" + dobMonth +
"/" + dobYear, 10, 130);
canvas.drawString( "Age: " + "19", 10, 170);
canvas.drawString( "Date: " + dd + "/" + mm + "/"+ yyyy, 10, 210);
canvas.paint();
32. Jack Eastwood
2.4 String operations
canvas.drawString( "Hello".bold());
canvas.drawString( "My name is
Jack Eastwood", 0, 20 );
canvas.drawString( " Hello" .link());
canvas.drawString( "My name is
Jack Eastwood", 0, 20 );
33. Jack Eastwood
// Ex2-4 : String operations
var canvas;
canvas = openGraphics();
canvas.drawString( "Hello".fixed());
canvas.drawString( "My name is
Jack Eastwood", 0, 20 );
canvas.drawString( "Hello".strike());
canvas.drawString( "My name is Jack
Eastwood", 0, 20 );
34. Jack Eastwood
var name = "Jack";
var nameLength;
nameLength = name.length;
canvas.drawString( "Number of characters in my name: ");
canvas.drawString( nameLength, 250, 0);
//aString.length calculates the number of characters assigned to a
variable
canvas.paint();
// Ex2-4 : String operations
var canvas;
canvas = openGraphics();
var name = "Jack";
var nameCharAt;
nameCharAt = name.charAt(3);
canvas.drawString( " 4th character of my name: ");
canvas.drawString( nameCharAt, 200, 0);
//aString.charAt() finds the specified character in a variable
i.e. charAt(0) finds the first character in a variable, in my case
it will be J
canvas.paint();
35. Jack Eastwood
// Ex2-4 : String operations
var canvas;
canvas = openGraphics();
var name = "Jack";
var nameCharAt;
nameCharAt = name.charAt(0) + name.substr(1);
canvas.drawString( " Separate 1st letter of my name from the rest: ");
canvas.drawString( name.charAt(0), 0, 30);
canvas.drawString( name.substr(1), 30, 30);
//aString.charAt() finds the specified character in a variable i.e.
charAt(0) finds the first character in a variable, in my case it will
be J
canvas.paint();
36. Jack Eastwood
// Ex2-4 : String operations
var canvas;
canvas = openGraphics();
var name = "jack";
var nameCharAt;
nameCharAt = name.charAt + name.substr;
canvas.drawString( " Separate 1st letter of my name from the rest:
");
canvas.drawString( name.charAt(0).toUpperCase(), 0, 30);
canvas.drawString( name.substr(1).toLowerCase(), 30, 30);
// .toUpperCase will select the 1st letter chosen from name.charAt
and will put it into upper case, whilst .toLowerCase will select
the other characters and put them into lower case.
canvas.paint();
37. Jack Eastwood
2.5 date operations
// Ex2-5
var canvas;
canvas = openGraphics();
var value;
var aDate;
aDate = new Date();
canvas.drawString( "The date is: " + aDate, 10, 20 );
value = aDate.toLocaleString();
canvas.drawString( "toLocalString: " + value, 10, 40 );
value = aDate.getYear();
canvas.drawString( "Year is: " + value , 10, 60 );
canvas.paint();
38. Jack Eastwood
// Ex2-5
var canvas;
canvas = openGraphics();
var value;
var aDate;
aDate = new Date();
canvas.drawString( "The date is: " + aDate, 10, 20 );
value = aDate.toLocaleString();
canvas.drawString( "toLocalString: " + value, 10, 40 );
value = aDate.getFullYear();
canvas.drawString( "Year is: " + value , 10, 60 );
value = aDate.getMonth();
canvas.drawString( "Month is: " + value, 10, 80 );
value = aDate.getDay();
canvas.drawString( "Day is: " + value, 10, 100 );
value = aDate.getDate();
canvas.drawString( "Date is: " + value, 10, 120 );
canvas.paint();
39. Jack Eastwood
// Ex2-5
var canvas;
canvas = openGraphics();
var value;
var aDate;
aDate = new Date( 1995, 6, 6);
canvas.drawString( "The date is: " + aDate, 10, 20 );
value = aDate.toLocaleString();
canvas.drawString( "toLocalString: " + value, 10, 40 );
value = aDate.getFullYear();
canvas.drawString( "Year is: " + value , 10, 60 );
value = aDate.getMonth();
canvas.drawString( "Month is: " + value, 10, 80 );
value = aDate.getDay();
canvas.drawString( "Day is: " + value, 10, 100 );
value = aDate.getDate();
canvas.drawString( "Date is: " + value, 10, 120 );
canvas.paint();
Ranges from 0-11 , 0=
January, 11= December
Day 1 = Monday, Day 7 = Sunday
40. Jack Eastwood
// Ex2-5
var canvas;
canvas = openGraphics();
var value;
var aDate;
aDate = new Date( 1995, 11, 25 );
canvas.drawString( "The date is: " + aDate, 10, 20 );
value = aDate.toLocaleString();
canvas.drawString( "toLocalString: " + value, 10, 40 );
value = aDate.getFullYear();
canvas.drawString( "Year is: " + value , 10, 60 );
value = aDate.getMonth();
canvas.drawString( "Month is: " + value, 10, 80 );
value = aDate.getDay();
canvas.drawString( "Day is: " + value, 10, 100 );
value = aDate.getDate();
canvas.drawString( "Date is: " + value, 10, 120 );
canvas.paint();
I was bornon a Thursday
41. Jack Eastwood
// Ex2-5
var canvas;
canvas = openGraphics();
var value;
var aDate;
Christmasin1995 was ona Monday
Put : insteadof ; at the endand only
supposedtoputa numberfrom0-9
42. Jack Eastwood
aDate = new Date();
value = aDate.setDate(29);
canvas.drawString( "Date is: " + value, 10, 20 );
value = aDate.setMonth(11);
canvas.drawString( "Month is: " + value, 10, 40 );
value = aDate.setFullYear(1980);
canvas.drawString( "Year is: " + value, 10, 60 );
canvas.paint();
The toLocaleStringcovertsthe newDate functioninto adate format,the getDate,getDay,getMonth
and getFullYearall retrievethe date fromthe computer’sclock.The setDate functionsallow the user
to inputthe day,monthand year,howeverthe outputis displayedinminutes,sothiswill needtobe
dividedtogetthe properdate,monthand year.
2.6 How old are you?
43. Jack Eastwood
// Ex2-6
var canvas;
canvas = openGraphics();
var day;
var month;
var year;
var birthday;
// get user's birthday details
// create two dates
day = parseInt(prompt( "Please enter your birthday: "), 10);
month = parseInt(prompt( "Please enter your birth month: "), 10);
year = parseInt(prompt( "Please enter your birth year: "), 10);
var aDate = new Date(year, month-1, day);
canvas.drawString ( "Date of birth: " + aDate, 10, 20);
var today = new Date();
canvas.drawString ( "Today's date: " + today, 10, 100);
var age = today - aDate;
canvas.drawString ("Your age: " + age, 10, 140);
var ageindays = age/86400000;
canvas.drawString( "Your age in days: " +ageindays.toFixed(0), 10,
180);
var ageinyears = ageindays/365;
canvas.drawString( "Your age in years: " + ageinyears.toFixed(0),
10, 220);
Identifierisdate1,notdate
45. Jack Eastwood
Comments
Thisasks the userto inputtheirbirthdate,monthand yearand formatit intoa date usingthe new
Date functionandplacingthe variableswithinthe (). Because Januaryisassignedto0 and December
is11, month-1is usedtomake the months1-12 insteadof 0-11.
2.7 Event timer
// Ex2-7: Event Timer
// This program calculates the difference in time
// between two events: the user clearing alerts
// The difference is a measure of the time it
// Takes to make two keypresses or mouse clicks
var canvas;
canvas = openGraphics();
// Put a Title on the output screen
canvas.setColor( "Yellow" );
canvas.setFont( "Comic sans ms", "30px", Font.UNDERLINE );
canvas.fillRect( 10, 10, 300, 200 );
canvas.setColor( "Red" );
canvas.drawString( "Timer",150,0 );
// uncomment the next line to see the title
// canvas.paint();
// create a Date object and store the current time
alert( "Press "OK" to start the timer." );
var date = new Date();
// create another Date object and store the time now
alert( "Press "OK" to stop the timer." );
var date1 = new Date();
var difference = date1 - date;
46. Jack Eastwood
canvas.setFont( "Comic sans ms", "20px" );
canvas.drawString( " Difference in time: " + difference + "ms",
10, 60);
// calculate the difference between the two times
// output a suitable message to the user
canvas.paint();
Comments
47. Jack Eastwood
Thisworksby pressingthe firstalertwindow will collectthe exactcurrenttime all the wayto
millisecondsandthe nextalertwindowwill alsocollectthe exactcurrenttime. Thisisthen
subtractedbythe variable calleddifference whichminus’sthe seconddate (“stoptimeralert”)
againstthe firstdate (“start timeralert”).
3.1 Grading work
// Ex: 3-1 Grading Work
var mark;
var grade;
grade = "Not Yet Graded";
mark = prompt( "Please input the mark(%)" );
mark = parseInt( mark, 10 ); // see comment
if( mark > 69 )
{
grade = "First Class";
}
else if ( mark > 59 )
{
grade = "Upper Class (2.1)";
}
else if (mark > 49 )
{
grade = "Lower Class (2.2)";
}
else if (mark > 39 )
{
grade = "Third Class";
}
alert( "Mark: " + mark + "% - Grade: " + grade );
53. Jack Eastwood
Comments
Thisprogram promptsthe userto input the grade percentage whichgetsparsedwithparseInt(),
thenthe IF statementssetsboundariesforthe inputi.e.if markisabove 70 thenthat’s a firstand if
the mark is between 50-59thena 2:2 isawarded.If a negative numberora numberover100 is
entered,thenthe program createsanalertthat the inputtednumberorcharacter isinvalid.
3.2 Date validation
54. Jack Eastwood
// Ex 2-3: Personal Details
var canvas;
canvas = openGraphics();
var name;
name = prompt( "Please enter your name:" );
Forgotto endwith} afterIF
statement
Forgotto put variable name after
&&
55. Jack Eastwood
var mobile;
mobile = prompt( "Please enter your mobile number: ");
var email;
email = prompt( "Please enter your email address: ");
var dobDay;
dobDay = prompt( "Please enter your birth day: ");
dobDay = parseInt(dobDay, 10);
var dobMonth;
dobMonth = prompt( "Please enter your birth month: ");
dobMonth = parseInt(dobMonth, 10);
var dobYear;
dobYear = prompt( "Please enter your birth year: ");
dobYear = parseInt(dobYear, 10);
var birthday;
birthday = new Date(dobYear, dobMonth-1, dobDay );
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var age;
age = today - birthday;
var ageindays;
ageindays = age/86400000;
var ageinyears;
ageinyears = ageindays/365;
canvas.setColor( "purple" );
canvas.fillRect(5, 5, 700 ,250);
canvas.setFont( "Arial" , "20px" );
canvas.setColor( "orange" );
canvas.setStroke( 5 );
canvas.drawRect(5, 5, 700, 250);
canvas.setColor( "pink" );
canvas.drawString( "Name: " + name, 10, 10);
canvas.drawString( "Mobile: " + mobile, 10, 50);
canvas.drawString( "Email: " + email, 10, 90);
canvas.drawString( "Date of birth: " + birthday, 10, 130);
canvas.drawString( "Age: " + ageinyears.toFixed(0), 10, 170);
canvas.drawString( "Date: " + today, 10, 210);
if (ageinyears.toFixed(0) == 20)
{
alert("Age is correct");
}
else if (ageinyears.toFixed(0) != 20)
{
alert( "Age is incorrect");
}
if (dobDay >=1 && dobDay<=31)
{
alert ("Day is valid");
56. Jack Eastwood
}
else
{
alert ("Day is invalid");
}
if (dobMonth >=1 && dobMonth <=12)
{
alert("Month is valid");
}
else
{
alert("Month is invalid");
}
if (dobYear > 0 && dobYear < 2015)
{
alert("Year is valid");
}
else
{
alert("Year is invalid");
}
canvas.paint();
Valid entries
59. Jack Eastwood
3.3 Coloured event timer
// Ex2-7: Event Timer
// This program calculates the difference in time
// between two events: the user clearing alerts
// The difference is a measure of the time it
// Takes to make two keypresses or mouse clicks
var canvas;
canvas = openGraphics();
// Put a Title on the output screen
canvas.setFont( "Comic sans ms", "30px", Font.UNDERLINE );
canvas.drawString( "Timer",150,0 );
// uncomment the next line to see the title
// canvas.paint();
// create a Date object and store the current time
alert( "Press "OK" to start the timer." );
var date = new Date();
// create another Date object and store the time now
alert( "Press "OK" to stop the timer." );
var date1 = new Date();
var difference = date1 - date;
canvas.setFont( "Comic sans ms", "20px" );
canvas.drawString( "Difference in time: ", 10, 60 );
if (difference <= 150)
{
canvas.setColor( "green" );
canvas.drawString( difference + "ms", 200, 60);
}
else if ( difference >=151 && difference <= 350 )
{
canvas.setColor( "orange" );
canvas.drawString( difference + "ms", 200, 60);
}
else if (difference > 350 )
{
canvas.setColor( "red" );
canvas.drawString( difference + "ms", 200, 60);
}
// calculate the difference between the two times
// output a suitable message to the user
canvas.paint();
61. Jack Eastwood
Comments
I separatedthe “difference intime:”fromthe resultdue tothe “difference intime:”alsobeing
coloured,sothiswouldhave beenputbefore the if statements.
3.4 Truth tables
AND Table
// Ex: 3-4
var canvas;
canvas = openGraphics();
62. Jack Eastwood
var operation;
operation = "AND";
var heading;
heading = "Truth Table for the " + operation + " operation.";
canvas.drawStringRect( heading.big(), 0, 5, 400, "center" );
var message;
message = "An entry in the table is the result of the operation ";
message = message + "A " + operation + " B";
canvas.drawStringRect( message, 0, 30, 400, "center" );
message = "i.e. result = a && b;";
canvas.drawStringRect( message, 0, 65, 400, "center" );
var x; // left edge of table
var y; // top of table
x = 50;
y = 100;
// draw table outline
canvas.setStroke( 3 );
canvas.drawLine( x, y, x+300, y );
canvas.drawLine( x, y, x, y+150 );
canvas.drawLine( x, y+50, x+300, y+50 );
canvas.drawLine( x, y+150, x+300, y+150 );
canvas.drawLine( x+100, y, x+100, y+150 );
canvas.drawLine( x+300, y, x+300, y+150 );
canvas.setStroke( 1 );
canvas.drawLine( x, y+100, x+300, y+100 );
canvas.drawLine( x+200, y, x+200, y+150 );
canvas.setStroke( Stroke.DOTTED );
canvas.drawLine( x, y, x + 100, y + 50 );
// Put in column and row labels
canvas.setFont( "lucida console", "20px", Font.BOLD );
canvas.setColor( "darkred" );
canvas.drawStringRect( "A", x+15, y+20, 50, "left" );
canvas.drawStringRect( "B", x+5, y+5, 80, "right" );
canvas.drawStringRect( "true", x, y+50+15, 100, "center" );
canvas.drawStringRect( "false", x, y+100+15, 100, "center" );
canvas.drawStringRect( "true", x+100, y+15, 100, "center" );
canvas.drawStringRect( "false", x+200, y+15, 100, "center" );
// Now to put the results in the table
var result;
var a;
var b;
canvas.setColor( "Darkblue" );
a = true;
b = true;
63. Jack Eastwood
result = a && b;
canvas.drawStringRect( result, x+100, y+50+15, 100, "center" );
a = true;
b = false;
result = a && b;
canvas.drawStringRect( result, x+200, y+50+15, 100, "center" );
a = false;
b = true;
result = a && b;
canvas.drawStringRect( result, x+100, y+100+15, 100, "center" );
a = false;
b = false;
result = a && b;
canvas.drawStringRect( result, x+200, y+100+15, 100, "center" );
canvas.paint();
OR Table
// Ex: 3-4
var canvas;
canvas = openGraphics();
var operation;
operation = "OR";
var heading;
heading = "Truth Table for the " + operation + " operation.";
canvas.drawStringRect( heading.big(), 0, 5, 400, "center" );
64. Jack Eastwood
var message;
message = "An entry in the table is the result of the operation ";
message = message + "A " + operation + " B";
canvas.drawStringRect( message, 0, 30, 400, "center" );
message = "i.e. result = a || b;";
canvas.drawStringRect( message, 0, 65, 400, "center" );
var x; // left edge of table
var y; // top of table
x = 50;
y = 100;
// draw table outline
canvas.setStroke( 3 );
canvas.drawLine( x, y, x+300, y );
canvas.drawLine( x, y, x, y+150 );
canvas.drawLine( x, y+50, x+300, y+50 );
canvas.drawLine( x, y+150, x+300, y+150 );
canvas.drawLine( x+100, y, x+100, y+150 );
canvas.drawLine( x+300, y, x+300, y+150 );
canvas.setStroke( 1 );
canvas.drawLine( x, y+100, x+300, y+100 );
canvas.drawLine( x+200, y, x+200, y+150 );
canvas.setStroke( Stroke.DOTTED );
canvas.drawLine( x, y, x + 100, y + 50 );
// Put in column and row labels
canvas.setFont( "lucida console", "20px", Font.BOLD );
canvas.setColor( "darkred" );
canvas.drawStringRect( "A", x+15, y+20, 50, "left" );
canvas.drawStringRect( "B", x+5, y+5, 80, "right" );
canvas.drawStringRect( "true", x, y+50+15, 100, "center" );
canvas.drawStringRect( "false", x, y+100+15, 100, "center" );
canvas.drawStringRect( "true", x+100, y+15, 100, "center" );
canvas.drawStringRect( "false", x+200, y+15, 100, "center" );
// Now to put the results in the table
var result;
var a;
var b;
canvas.setColor( "Darkblue" );
a = true;
b = true;
result = a || b;
canvas.drawStringRect( result, x+100, y+50+15, 100, "center" );
a = true;
b = false;
result = a || b;
canvas.drawStringRect( result, x+200, y+50+15, 100, "center" );
65. Jack Eastwood
a = false;
b = true;
result = a || b;
canvas.drawStringRect( result, x+100, y+100+15, 100, "center" );
a = false;
b = false;
result = a || b;
canvas.drawStringRect( result, x+200, y+100+15, 100, "center" );
canvas.paint();
Comments
The difference betweenANDandORisthat ANDoperationsare definedby&&between2variables
whilst||isusedto define OR.
3.5 Experiments with graphics
// Ex3-5 : Graphics Experiments
// Part of demo program:
var canvas;
canvas = openGraphics();
var x;
var y;
var size;
x = 0;
y = 0;
size = 500;
66. Jack Eastwood
while( size > 0 )
{
canvas.setColor( "white" );
canvas.fillEllipse( x, y, size, size );
canvas.setColor( "blue" );
canvas.drawEllipse( x, y, size, size );
x = x + 10;
y = y + 10;
size = size - 20;
}
canvas.paint();
// Ex3-5 : Graphics Experiments
// Part of demo program:
var canvas;
canvas = openGraphics();
var x;
var y;
var width;
67. Jack Eastwood
var height;
x = 0;
y = 0;
width = 200;
height = 700;
while( (width > 0 ) && (height > 0) )
{
canvas.setColor( "white" );
canvas.fillEllipse( x, y, width, height );
canvas.setColor( "blue" );
canvas.drawEllipse( x, y, width, height );
x = x + 23;
y = y + 3;
width = width - 7;
height = height - 70;
}
canvas.paint();
69. Jack Eastwood
var canvas;
canvas = openGraphics();
var textX = 20;
var textY = 30;
var lineX = 180;
var lineY = textY + 5;
for (var i = 0; i < 10; i++) {
// Put your event timer code here
alert( "Press "OK" to start the timer." );
var date = new Date();
// create another Date object and store the time now
alert( "Press "OK" to stop the timer." );
var date1 = new Date();
var difference = date1 - date;
var previoustime;
canvas.setStroke(3);
canvas.setColor("black");
canvas.drawString( "Timer", 150, 0 );
canvas.drawString( " Difference in time: " + difference +
"ms", 10, textY);
if (previoustime>difference) {
canvas.setColor("Green");
}
else if (previoustime<difference){
canvas.setColor("Red");
}
else {
canvas.setColor("black");
}
canvas.drawLine( lineX, lineY, lineX + difference, lineY );
textY = textY + 20;
lineY = lineY + 20;
previoustime=difference;
canvas.paint();
}
70. Jack Eastwood
3.7 Sudoku Grid
// Ex3-7 : Blank Sudoku Grid
var canvas;
canvas = openGraphics();
var x;
var y;
var gap;
x = 20;
y = 20;
gap = 25;
// so not much help here!
var count;
for( count=0; count<11; count++ )
{
canvas.drawLine( x,y,x+225,y );
y = x+count*gap;
} //endfor
x = 20;
y = 20;
for( count=0; count<11; count++ )
{
canvas.drawLine(x,y,x,y+225);
x = y+count*gap;
}
x = 20;
y = 20;
for( count=0; count<5; count++ )
{
canvas.setStroke(3);
canvas.drawLine(x,y,x+225,y);
y = x+count*gap*3;
}
71. Jack Eastwood
x = 20;
y = 20;
for( count=0; count<5; count++)
{
canvas.setStroke(3);
canvas.drawLine(x,y,x,y+225);
x = y+count*gap*3;
}
canvas.paint();
72. Jack Eastwood
4.1 Garfield cartoon
// Ex4-1: Garfield Cartoon
var canvas;
canvas = openGraphics();
var imageName1;
var imageName2;
var imageName3;
var xPosition;
var yPosition;
var width;
var height;
imageName1 = "garfield1.gif";
xPosition = 10;
yPosition = 10;
canvas.drawImage(imageName1, xPosition,yPosition);
imageName2 = "garfield2.gif";
xPosition = 210;
yPosition = 10;
canvas.drawImage(imageName2, xPosition, yPosition);
imageName3 = "garfield3.gif";
xPosition = 400;
yPosition = 10;
canvas.drawImage(imageName3, xPosition, yPosition);
canvas.setFont( "comic sans ms","10.5px", Font.BOLD );
canvas.drawStringRect("THERE'S A GOOD SCARY MOVIE ON TV TONIGHT",
30, 13, 150);
canvas.drawStringRect("YEAH, SURE", 140, 55, 50);
canvas.drawStringRect("YOU SAY THAT EVERY NIGHT", 328, 40, 61);
canvas.drawStringRect("''INVASION OF THE 50-FOOT ADOLESCENTS''",
415, 12, 150);
canvas.drawStringRect("TONIGHT, THOUGH, YOU WOULD BE CORRECT",
530, 40, 70);
canvas.paint();
73. Jack Eastwood
4.2 guess the number
// Ex4-2: Guess the Number
var canvas;
canvas = openGraphics();
var max;
max = 100;
var numberToGuess;
numberToGuess = 50; // use a known value for testing
canvas.drawString("Welcome to Jack Eastwood's guessing game", 50,
10);
var guess;
guess = parseInt(prompt("Please input a number between 0 and
100"),10);
var guessed = false;
var message;
// (3) if too high .....
if (guess < numberToGuess)
{
canvas.drawString("You was wrong, try a higher
number", 10, 30);
}
// (4) if too low .....
if (guess > numberToGuess)
{
canvas.drawString("You was wrong again fool, try a
lower number", 10, 30);
}
// (5) "just right" said Goldilocks .....
if (guess == numberToGuess)
{
canvas.drawString("You was right",10,30);
}
// (6) canvas.drawString( message ......
75. Jack Eastwood
// Ex4-2: Guess the Number
var canvas;
canvas = openGraphics();
var max;
max = 100;
var numberToGuess = Math.floor( Math.random() * max ) +1;
canvas.drawString("Welcome to Jack Eastwood's guessing game", 50,
10);
var x = 20;
var y = 20;
var guess;
var guessed = false;
while( !guessed ){
guess = parseInt(prompt("Please input a number
between 0 and 100"),10);
var message;
// (3) if too high .....
if (guess > numberToGuess){
message = guess + " Too high";
}
// (4) if too low .....
if (guess < numberToGuess) {
message = guess + " Too low";
}
// (5) "just right" said Goldilocks .....
if (guess == numberToGuess) {
message = guess + " Correct";
76. Jack Eastwood
guessed = true;
}
canvas.drawString( message, x, y);
y = y + 20;
canvas.paint();
}
4.3 Square root calculator
// Ex4-3 : Square Root Calculator
var canvas;
canvas = openGraphics();
//var number = prompt( "Enter a number: " );
//number = parseInt( number, 10 );
//var sqRoot;
//sqRoot = Math.sqrt( number );
77. Jack Eastwood
//var message;
//message = "Using the JavaScript library,<br>";
//message = message + "The square root of " + number + "<br>";
//message = message + "is " + sqRoot;
// Put your version here
var lowGuess = 0;
var highGuess = 10;
var squareRoot = Math.sqrt( highGuess );
var guess = prompt( "Please enter a number: ");
var message;
if( guess > squareRoot){
message = guess + " Too high";
}
if( guess < squareRoot){
message = guess + " Too low";
}
if( guess == squareRoot){
message = guess + " Correct";
}
canvas.drawString( message, 10, 10 );
canvas.paint();
4.4 BMI calculator
// Ex4-4: BMI Calculator
var canvas;
canvas = openGraphics();
var height = 160/100;
var weight = 40;
var bmi = weight/(height * height);
alert( bmi );
canvas.paint();
// Ex4-4: BMI Calculator
var canvas;
canvas = openGraphics();
78. Jack Eastwood
canvas.setFont( "Comic Sans MS", "20px", Font.BOLD );
canvas.drawString( "BMI calculator bitch's", 150, 0);
var height = parseFloat(prompt("Please enter your height in cm: ")
,10)/100;
var weight = parseFloat(prompt("Please enter your weight in kg: ")
,10);
var calculation = weight/(height * height);
var bmi = calculation.toFixed(2);
var classification;
if (bmi <= 18.4999){
classification = " Underweight";
}
else if (bmi > 18.4999 && bmi <= 24.999){
classification = " Ideal";
}
else if (bmi > 24.999 && bmi <= 29.999){
classification = " Overweight";
}
else if (bmi > 29.999 && bmi <= 39.999){
classification = " Obese";
}
else if (bmi > 39.999){
classification = " Very obese";
}
canvas.setFont( "Comic Sans MS", "14px" );
canvas.drawString( bmi + ":" + classification, 0, 50 );
canvas.paint();
80. Jack Eastwood
// Ex4-4: BMI Calculator
var canvas;
canvas = openGraphics();
var reset = false;
var xos = 20;
var xosGreen = 125;
var xosOrange = 205;
var xosBrown = 265;
var xosRed = 385;
var yos = 20;
var lineHeight = 400;
var lineHeight2 = 396.5;
var lineLength = 550;
var lineYellow = 105;
var lineGreen = 80;
var lineOrange = 60;
var lineBrown = 120;
var lineRed = 185;
var label = 10;
var labelnum = 0;
var ArmLength = 30;
var ArmYPos = 330;
var LArmPos = 265;
var RArmPos = 320;
var LegLength = 70;
var LegYPos = 350;
var LLegPos = 300;
var RLegPos = 320;
while( !reset ){
canvas.setFont( "Comic Sans MS", "20px", Font.BOLD
);
canvas.drawString( "BMI calculator bitch's", 150,
0);
canvas.setFont( "Comic Sans MS", "14px");
canvas.drawString( "This program will calculate
your body mass index which is an indication of the status of your
weight.", 0 ,30 );
canvas.drawString( "The higher the BMI figure, the
more likely it is that you are overweight.", 0, 50);
var height = parseFloat(prompt("Please enter your
height in cm: ") ,10)/100;
var weight = parseFloat(prompt("Please enter your
weight in kg: ") ,10);
88. Jack Eastwood
5.5 Bmi calculator html
<html>
<head>
<title>
BMI Calculator
</title>
</head>
<body>
<h1> BMI calculator </h1>
<p> Body Mass Index is derived from calculating an
individuals weight and height. The calculation to work out an
individuals BMI for a metric conversion is weight/height x height.
</p>
<p> There are classifications for different bmi
values: </p>
<p> 18.5 or under: Underweight </p>
<p> 18.5 - 25: Ideal </p>
<p> 25 - 30: Overweight </p>
<p> 30 - 40: Obese </p>
<p> 40 or over: Very Obese </p>
<form id="weight" action="server_program_name"
method="get">
<label for="weight">
Please enter your weight (KG):
</label>
<input type="number" name="weight" min="0"></form>
<form id="height" action="server_program_name"
method="get">
<label for="height">
Please enter your height (CM):
</label>
<input type="number" name="height" min="0"></form>
<button value="submit" type="submit">
Calculate BMI
</button>
</body>
</html>
89. Jack Eastwood
6.1 Metric Conversion
<html>
<head>
<title>
Metric Conversions
</title>
<script type = "text/JavaScript">
function milesToKilometers()
{
var miles;
miles = document.getElementById(
"milesBox" ).value;
miles = parseFloat( miles );
var kilometers = miles / 5 * 8;
document.getElementById( "kilometersBox"
).value = kilometers.toFixed(2);
}
function KilometersToMiles()
{
var kilometers;
kilometers = document.getElementById(
"kilometersBox" ).value;
kilometers = parseFloat( kilometers );
90. Jack Eastwood
var miles = kilometers / 8 * 5;
document.getElementById( "milesBox" ).value
= miles.toFixed(2);
}
</script>
</head>
<body>
<h1>
Metric Conversions
</h1>
<h2>
Miles : Kilometers
</h2>
<p>
The conversion factor for miles and
kilometers
is based on the fact that 5 miles is the
same
distance as 8 kilometers.
</p>
Miles:
<input type = "text"
id = "milesBox"
value = "" />
<br />
Kilometers:
<input type = "text"
id = "kilometersBox"
value = "" />
<br /><br />
<input type = "button"
id= "convert1"
value = "Miles to Kilometers"
onclick = "milesToKilometers();" />
<br /><br />
<input type = "button"
id = "convert2"
value = "Kilometers to Miles"
onclick = "KilometersToMiles();" />
</body>
</html>
91. Jack Eastwood
6.2 Interest Calculator Page
<html>
<head>
<title>
Interest Calculator
</title>
<script type = "text/Javascript">
92. Jack Eastwood
function InterestCalculator()
{
var amount;
amount = document.getElementById( "money").value;
amount = parseFloat( amount );
var rate;
rate = document.getElementById( "Interest_rate" ).value;
rate = parseFloat( rate );
var years;
years = document.getElementById( "Investment_period"
).value;
years = parseFloat( years );
// declare, and initialise, identifiers for rate and time
var interest;
interest = (amount * rate * years)/100;
// input a formula to calculate the interest
//250 x 10=2500 x 1 = 2500/100=25
alert( interest );
}
</script>
</head>
<body>
<h1> Interest Calculator </h1>
<p> This will calculate the interest on any amount of money
from the interest rate and investment period. </p>
<form action="server_program_name" method="get">
<label for="money">
Amount of money:
</label>
<input type="number"id="money" name="money"></form>
<form action="server_program_name" method="get">
<label for="interest_rate">
Interest rate(%):
</label>
<input type="number" id="Interest_rate"
name="money"></form>
<form action="server_program_name" method="get">
<label for="investment_period">
Investment period (years):
</label>
<input type="number" id="Investment_period"
name="Investment money" min="0">
<br /><br />
<input type = "button"
id = "CalculateInterest"
value = "Calculate Interest"
onclick = "InterestCalculator();" />
</form>
</body>
</html>
94. Jack Eastwood
6.3 Validating a date
<html>
<head>
<title>
Date Validation
</title>
<script type = "text/Javascript">
function DateValidation()
{
var day;
day = document.getElementById( "day" ).value;
day = parseFloat( day );
var month;
month = document.getElementById( "month" ).value;
month = parseFloat( month );
var year;
year = document.getElementById( "year" ).value;
year = parseFloat( year );
var today = new Date();
95. Jack Eastwood
var tDay = today.getDate();
var tMonth = today.getMonth()+1;
var tYear = today.getFullYear();
var birthday;
birthday = new Date( year, month-1, day );
var age;
age = today - birthday;
var ageindays;
ageindays = age/86400000;
var ageinyears;
ageinyears = ageindays/365;
if (day >=1 && day<=31)
{
alert ("Day is valid");
}
else
{
alert ("Day is invalid");
}
if (month >=1 && month <=12)
{
alert("Month is valid");
}
else
{
alert("Month is invalid");
}
if (year >= 0 && year <= 2015)
{
alert("Year is valid");
}
else
{
alert("Year is invalid");
}
document.getElementById( "ageBox" ).value =
ageinyears.toFixed(2);
}
</script>
</head>
<body>
<h1> Date validation </h1>
<p> Page to validate the user's birthday</p>
<form action="server_program_name" method="get">
<label for="day">
Day:
</label>
<input type="number" name="money" id="day"
min="1"></form>
<form action="server_program_name" method="get">
<label for="month">
Month:
</label>