Key Words: function, method, procedure,
form control, input
, id
, onchange
,
event handler, function call, function definition, function head,
formal parameter, function body, variable, variable declaration,
assignment operator, assign, getElementById()
, value
,
text, string of characters, +
, string concatenation,
string, innerHTML
.
See Wikipedia (http://www.wikipedia.org/) for a
detailed description of the key words.
You are required to have completed the objectives in Lab 06 before starting this lab.
Remember to use the online resources! When you encounter a new HTML element, look at W3Schools HTML and XHTML tutorials, and W3C's HTML recommendations. When you encounter a Javascript function or want to find what you can do with an HTML element in your JavaScript code, look at W3Schools JavaScript tutorial and W3Schools DHTML/DOM (Dynamic HTML/Document Object Model) tutorial. You do not need to understand everything in their tutorials, but you should at least know where to find help.
In the previous section you successfully had a browser run your JavaScript code. In this section you will learn how to use HTML to get information from the user through a graphical user interface (GUI) and how to use that information in your JavaScript code to change the contents of a web page.
lab8.html
file with the usual HTML framework.body
element.
The paragraph should include a text asking for the user's first name
followed by an input
element (also called form
control since it is widely used in web forms for users to fill
out):
<p>
Your first name please:
<input id="firstNameField" type="text" onchange="fixOutput()">
</p>
This input
element:
id
attribute which you can use to refer
to this element later on (e.g., in your JavaScript code). type
attribute with a value of text
, which tells the browser to display a text field that can be
edited by the user. onchange
attribute that tells the
browser what should happen if the content of the text field is changed
(and left) by the user. The onchange
value is sometimes
called an event handler since it tells the browser how to
handle events, or actions. In this case the browser will use (or call)
the JavaScript function fixOutput()
when there is a
change (event) in the text field. The fixOutput()
function does not exist yet. You will soon write it. Document (add comments), save, publish (i.e. copy into your student web site), validate, and view your enhanced document through a browser. Correct any errors.
Tab
key or clicking outside the text
field), nothing happens. This is because the JavaScript function fixOutput()
is not known by the browser yet. By contrast, you didn't have to tell
the browser about the alert()
function -- the browser has
that built in.
A function is a description of steps defined in one place and used (or called) from another place in your code. It is very much like a recipe: you write it once, but can use/follow it over and over again (given you have the required ingredients). A function can also be used/called by other functions in the same way that you can write some base recipe that can be used in other recipes: a pie dough recipe can be used by many different pie recipies.
Functions must be written, or defined before they can
be used/called for the first time. It's good to get the browser to read
them in early, before it starts laying out the page's body. For HTML
documents, this means that the functions should be defined in the
document's head.
It is often a good idea to define all your functions in a separate
file, so you can reuse them from many pages. If you put them in a
file, then give the file the extension .js
-- this will
indicate it contains JavaScript code. You can include the code
from the file by using a src
attribute in the script
tag.
Add this definition of the function fixOutput()
in the
document's head:
<script type="text/javascript">
function fixOutput() {
alert("Running function fixOutput()");
}
</script>
Every function definition in JavaScript must begin with a function head that consists of:
function
", After the head comes the function body, which includes
an opening curly bracket "{
", some content/statements, and
a closing curly bracket "}
". (You'll note we're
using the words "head" and "body" to describe parts of functions and
also parts of HTML pages...)
Save and reload your lab8.html
in a browser. Enter
some text in the input field and leave the field. When the cursor
leaves the (changed) input field, the browser will call your fixOutput()
function. The function will then run its code and, in this case, cause
an alert window to appear!
If this did not happen, check the following list of common errors:
onchange
attribute does not correspond to
the correct function. Verify the name of the function and fix if
incorrect. Remember that UPPERCASE and lowercase are not the
same. Do not forget the parentheses. src
attribute (if you are using one) does not refer to the correct
file. Verify the name of the file and fix if incorrect. Remember that
UPPERCASE and lowercase are not the same. The list of common errors is something you should always check when you encounter an error or any strange behavior. Many programming errors result from simple things like spelling errors or using at an old version of their file (due to forgetting to save after the latest changes).
When everything works as intended you can brag a little: You have just written a complete computer program that accepts user input through a graphical user interface (GUI) and gives feedback to the user. And you have done so by using a function, a feature that most beginners have problems with!
However, before you are done with the lab, your program should do something with the user's name and update the contents of the web page.
In this section we'll be modifying and re-displaying the user's
name. Here's a little background on what we'll do to the name:
In northern Europe some thousand years ago people that called themselves nordbor (Swedish for "people who live in the North") went out on trips to "convince" other people to give them gold and other valuables. This behavior was given the term "gå i viking" ("Go on a long trip") which later made these people known as Vikings.
fixOutput()
function to show the
message "I have some interesting news for you.
" instead of
the rather dull old message. Verify that it works as intended.Variables (like functions) do not exist until they are declared in the JavaScript code. Unlike functions, variables do not need to be defined -- they do not need to have their value specified right away when they're declared. (You can think of a function's body as its "value".)
At the end of the body of your fixOutput()
function (on an empty line right above the closing curly bracket '}'),
add the following statement:
var firstName;
This is a variable declaration! The rest of the statements in
the fixOutput()
function can now use the
"bucket"/variable named firstName
to store things in.
Note that the variable name (like function names) cannot have spaces,
which is why we capitalize "N
" in "firstName
".
It makes the names easier to read.
firstName = document.getElementById("firstNameField").value;
This is quite complicated but can be understood by examining it in pieces. The entire statement has three parts:
firstName
,
that will be used to store something. =
". The assignment operator executes the expression on the righthand side and stores the result in the variable on the lefthand side. Or, put another way, the variable on the lefthand side is assigned the value calculated from the righthand side.
The righthand side can be understood by reading it from left to
right: "Call the document
's getElementById()
function with the argument "firstNameField"
, and once
that is done, take the value
from the
result".
You need to have some creativity to figure out what the document
's
getElementById()
function does. Given an id
,
the function gets the corresponding element in the document. So the
browser looks through your HTML document and tries to find an element
that has an id attribute with the value "firstNameField"
.
Go
to your HTML document and you will see that you have an input
element that has an id
attribute with the value "firstNameField
".
Therefore, getElementById("firstNameField")
will get this
particular input
element.
The value
located after getElementById("firstNameField")
tells the browser to extract the value (text) that the user typed into
the text field. The value, in this case, will be a name (a string
of characters).
Nothing new should happen. So how can you verify that everything
works? One good way is to add an alert message that shows the entered
name. Add the following statement to the end of the fixOutput()
function body:
alert("Your name: " + firstName);
Notice how you can use "+
" to join (concatenate)
two things together. In this case, you are concatenating a string of
characters, "Your name: ", with the contents of the variable firstName
(another string of characters). Expressions within parentheses are
always executed first, like in mathematics. So the alert()
function will, therefore, receive the concatenated result, and show the
result in the alert window.
Document (add comments), save, publish, validate, and try your
program! When it works as intended you can remove the last alert()
statement.
fixOutput()
function
change the contents of an element in your web page! Begin by ensuring
that you have an element that you can refer to by its id. Add a
paragraph in your lab8.html
. It should be placed in the
body of the page, right before the </body>
end tag:
<p id="output">
</p>
Note that the element contains an id
attribute,
which gives a name to the element that you will use when you want to
refer to that particular element in your JavaScript
code.
Now you can tell the browser to put new text right there in the
paragraph called output
. Here's how: Add the
following lines to the end of your fixOutput()
function (inside the function body):
var elementToChange = document.getElementById("output");Why is that backslash in there? Without it, the browser would try to interpret the / as some HTML code right there while it's reading in the page head, not later when the JavaScript function is run. The backslash "quotes" the following character, so the browser treats it as ordinary text while reading in the page.
elementToChange.innerHTML =
"If you were a <em>real Viking<\/em>, your son's last name would be " +
firstName + "sson " +
"and your daughter's last name would be " +
firstName + "sdottir!";
fixOutput()
function does. (Place the comment
immediately above the line you are explaining.) Answer questions like
what is elementToChange
and what is it for? What is the innerHTML
for? Discuss the function with your fellow students! You can find
information about innerHTML
in the DOM section of
W3Schools DHTML Tutorial. This lab is worth 20 points and 6 points extra credit are available.
Item | Points |
Alert: "Running function..." | 4 |
Alert: 'Your name is...' and correct name | 6 |
"If you were a real Viking...." paragraph with correct names | 6 |
Comments explaining code | 4 |
Extra credit: Validate as XHTML 1.0 with icons | 6 |
The Word document should include your name, student number, UW NetID, lab section, and URL for your Web page. If you prefer, you can use a .txt file instead of a Word doc.
WARNING: Do NOT work on your lab after the deadline or it will be considered late and you will not receive credit. After the deadline, if you want to make an improvement or correction, make those changes on a copy of your file. That way, you can learn and test changes without losing credit for the lab.
Due Date: Tuesday, February 19, before 5pm.