Our First JavaScript Programs
Computing Concepts, Fall 2001,
Tom Linton
This file can be accessed on-line at
http://www.central.edu/homepages/lintont/classes/fall01/concepts/program1/program1.html.
For starters, let's set up our K drive for the rest of this semester.
In your homework folder, make a subfolder and name it javascript (lowercase,
no caps). In the javascript folder, make a subfolder named lesson10. Save
all of the HTML files you use for assignments in lesson 10 in this folder.
Thus far, we only know JavaScript statements that:
-
declare a variable: var someMeaningfulName;
-
assign a value to a variable: name="Tom";
-
write text or HTML to our document: document.write("Hello
big happy world!");
We also know the following JavaScript commands (which
cannot stand on their own as statements), which can be combined and used
as the right hand side of an assignment statement.
-
To convert a String into a number we use parseFloat(num1)
-
To get some input from the user we use prompt("Question
String","Answer String")
-
To concatenate Strings, just add them: "Hello
there " + name + ", <BR>how are you today?"
-
Use the standard symbols to do arithmetic: (num1
+ num2) / (12 * monthlyTotal)
Finally, our JavaScript statements must go in the
HEAD or BODY of our HTML file, and be enclosed in SCRIPT tags. Our default
JavaScript program file will look like this:
<HTML>
<HEAD>
<TITLE>My Program</TITLE>
<SCRIPT LANGUAGE="JavaScript"><!--
//--></SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
You may want to copy the above template HTML and
save it a file named something like js.html, so for each program you go
to write, you can simply open up js.html, perform a Save As operation
to re-name the file and start typing in the JavaScript you need to solve
the problem at hand.
It turns out that FrontPage can help a bit in
writing JavaScript programs. If you use the HTML tab to type in
the HTML directly, and then use the Preview tab, FrontPage will
report the line number of any syntax errors you may have.
Without looking at your text, try to write programs
to perform the following tasks.
-
Ask the user for a day of the week, a name of a friend,
a favorite color, and a favorite food (one at a time), then print the following
two lines, with their responses replacing the italics text (but their responses
are not in italics).
Last day, friend ate a big plate of food,
and turned color!
Be sure to use two lines for this printing, and their food should be in
a red font. Save
your results in a file named food.html.
-
Ask the user for their name, then, using their name
in the prompt, ask them for a number of quarters, dimes, and nickels (one
at a time) and then print the following sort of summary (with their numbers
being used).
Well name, you have 3 quarters, 2 dimes,
and 4 nickels, which is a total of 9 coins worth 115 cents.
Save your results in a file named coins.html.
Add links from your homework page to
these javascript assignments as explained in lesson 9 thread A.