Getting Started With JavaScript

David Marcovitz

Resources

While this document is under construction, you might want to refer to some more complete resources. An excellent introduction to JavaScript can be found at:

http://www.webteacher.com/javascript/ - JavaScript: a tutorial "for the TOTAL non-programmer"

Answers to questions about JavaScript can be found (or asked if they are not there) at the JavaScript newsgroup, comp.lang.javascript or through Google groups at:

http://groups.google.com/group/comp.lang.javascript/topics

Finally, a very simple tutorial can be found at:

http://www.ion.uillinois.edu/institutes/fsi/2000/javascript/ - JavaScript for Educators

Getting Started

If you have already used HTML, you know that your Web page is divided into a HEAD and a BODY. The HEAD contains information that does nto appear on the main part of the page, and the BODY contains the information that does appear on the page. JavaScript fits nicely into this model because for most of the things that you do you will have the "behind-the-scenes" scripts in the HEAD section of your document, and the forms that are displayed (including buttons and input boxes) in the BODY of your document. When you enter text into a form, or click on a button, the script (from the HEAD) will run to do the magic.

Start your HEAD section by telling the browser that you want to use JavaScript:

<SCRIPT language="JavaScript">

At the end of your script you will conclude by closing the SCRIPT tag:

</SCRIPT>

The script itself (that's the magic that tells the computer what to do when a button is pressed or other action is taken) goes between the <SCRIPT> tag and the </SCRIPT>. Because you don't want the script to be displayed on your computer, you will hide the script inside a comment tag, so after the <SCRIPT>, add:

<!--

and before the </SCRIPT> add:

-->

Now, the beginning of your page will look something like this:

<HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--

//The script will go here.

-->
</SCRIPT>
</HEAD>

Setting Up the File

You can always display forms in your body with basic HTML tags, but they can't do anything interesting without JavaScript. The two main tags you need are the FORM and INPUT tags. All other parts of your document can use standard HTML tags. Each form in your document will start with the <FORM> tag and end with </FORM>. The <FORM> tag will contain a name that can be used by the JavaScript to manipulate parts of the form. For example,

<FORM NAME="MyFirstForm">


</FORM>

Inside the form, you can put active elements and standard HTML. The active elements generally use the INPUT tag. The TYPE parameter tells the INPUT tag what kind of active element to display.

Buttons

The simplest INPUT element is a button. The button uses the parameter TYPE="button". To allow JavaScript to manipulate the button, you will want to give it a name with the NAME parameter and have text in the button with the VALUE parameter

<FORM NAME="MyFirstForm">
<INPUT TYPE="button" NAME="MyButton" VALUE="Click Me">
</FORM>

But this won't do anything until a script is written that knows to do something when the button named MyButton is clicked. This requres our button to have an ONCLICK parameter linked to a script:

<FORM NAME="MyFirstForm">
<INPUT TYPE="button" NAME="MyButton" VALUE="Click Me" ONCLICK="SayHello()">
</FORM>

This will run the script named SayHello when the button is clicked. For this to work, we better write a SayHello script and put it in the HEAD in the SCRIPT area. Here is a how our file will look:

<HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--
function SayHello()
{
alert("Hello");
}
-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="MyFirstForm">
<INPUT TYPE="button" NAME="MyButton" VALUE="Click Me" ONCLICK="SayHello()">
</FORM>
</BODY>
</HTML>

Note that the script, which you don't see and which is betweeen the <SCRIPT> and </SCRIPT> is in the HEAD, and the form, which you do see and is between the <FORM> and </FORM> is in the BODY. Click here to see this example. Click the Back button in your browser when you want to return here.

The script in this case is a simple script that pops up an alert that says "Hello." Change the text between the quotes, and it can say whatever you want.

Simple Multiple-Choice Quiz

Now that you have the ability to make buttons, you can make a simple multiple-choice quiz. Use standard HTML, to put the text for a question, the INPUT tag to create the buttons (using standard HTML elements, such as tables, to line up the buttons), and have each button linked to a script that announes "Right Answer" or "Wrong Answer." Click here to see an example, and see the HTML file below.

 <HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--
function RightAnswer()
{
alert("Good job");
}
function WrongAnswer()
{
alert("Try Again");
}
-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="SimpleQuiz">
<H1>Who was the first president of the United States?</H1>
<INPUT TYPE="button" NAME="George" VALUE="George Washington" ONCLICK="RightAnswer()">
<INPUT TYPE="button" NAME="Abe" VALUE="Abraham Lincoln" ONCLICK="WrongAnswer()">
<INPUT TYPE="button" NAME="Jefferson" VALUE="Jefferson Davis" ONCLICK="WrongAnswer()">
</FORM>
</BODY>
</HTML>

Getting Input

An INPUT of type TEXT can be used to create a text box:

<INPUT TYPE="TEXT" NAME="MyTextBox" SIZE="50">

In this case, both the NAME and SIZE parameters are very important.The NAME parameter is important because the script will use the name of the textbox to get use what was typed into it by the user. The SIZE is important because the text box does not have text in it to start, so the browser doesn't know how big to make it unless you tell it.

Simply putting the above INPUT tag somewhere in your BODY will put a text box that can be typed into, but you will need more to use the text that is typed.

Accessing the text that is in the text box requires the following in your script: document.FormName.TextBoxName.value, replacing "FormName" with the name you give the form (in the FORM tag) and "TextBoxName" with the name you give the text box (in the INPUT tag). This could go in a script, such as:

function SayHello()
{
alert("Hello, " + document.NameForm.NameBox.value);
}

Next, we need a button that will run the script and some text to tell the user what to put in the script. All this can go into a form:

<FORM NAME="NameForm">
<P>Please type your name:</P>
<INPUT TYPE="text" NAME="NameBox" SIZE="50">
<BR>
<INPUT TYPE="button" NAME="EnterName" VALUE="OK" ONCLICK="SayHello()">
</FORM>

Put this all together into one file (click here to see the file):

<HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--
function SayHello()
{
alert("Hello, " + document.NameForm.NameBox.value);
}
-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="NameForm">
<P>Please type your name:</P>
<INPUT TYPE="text" NAME="NameBox" SIZE="50">
<BR>
<INPUT TYPE="button" NAME="EnterName" VALUE="OK" ONCLICK="SayHello()">
</FORM>
</BODY>
</HTML>

If Statements and Short-Answer Questions

Clicking on a button is helpful, but sometimes you might want to do something based on something other than which button is pressed. For example, you might want to do something based on what the user types in. That is, if the user types one thing, do something, and if the user types something else, do another thing. For this, you will need an IF statement in your script. This could be used for a simple short-answer question. We can compare what is typed in the text box to the correct answer and do something based on whether they match or not. An IF statement asks a question and does something if the answer to the question is yes (or TRUE). It can also ask additional questions if the answer is no (or FALSE). Finally, it can have an ELSE section in case none of the questions' answers is yes (or TRUE).

In a short-answer question, we might want to ask what the capital of Maryland is. When the user types an answer and clicks on a button, we can ask if what the user typed (remember the statement: document.FormName.TextBoxName.value) is equal to the right answer. In English, we might have the user type the answer to the question "What is the capital of Maryland?" Our script will ask:

If what the user typed is equal to "Annapolis" then
Say "Good job"
Otherwise
Say "Try again"

Don't type that because it is not in JavaScript, but it is easy to convert to JavaScript:

    if (document.Capital.yourAnswer.value == "Annapolis") 
{
alert("Good job!")
}
else
{
alert("Try again.")
document.Capital.yourAnswer.select()
}

Note that "is equal to" is two equal signs. Also note the added trick, document.Capital.yourAnswer.select(), which leaves the text box selected so when the user types a new answer, it will automatically be entered into the right place. Also note that the name of the form will be Capital, and the name of the text box will be yourAnswer. Here is the code from the file (click here to see the file):

<HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--
function CheckCapital()
{
if (document.Capital.yourAnswer.value == "Annapolis")
{
alert("Good job!")
}
else
{
alert("Try again.")
document.Capital.yourAnswer.select()
}
}
-->
</SCRIPT>
</HEAD>
<BODY>
<FORM name="Capital">
<H1>What is the capital of Maryland?</H1>
<INPUT type="text" name="yourAnswer" size="50">
<INPUT type="button" name="enterCapital" value="Check your answer" onClick="CheckCapital()">
</FORM>
</BODY>
</HTML>

Variables

Sometimes you will want to store some information as you go along. For this, you will need a variable. This could be used to keep track of a score on a quiz or what has been done in the past. A variable is a place (think of it as a little box in the computer's memory) to store things. To use a variable you need to declare it (that is, tell the computer that you want to use a variable). You do this at the very beginning of your script with the VAR command:

var myVariable

This sets aside some space where the computer can remember what you want to store. When you get more advanced, you might use different types of variables to store different types of things, but for now, you don't have to specify what type of thing you want to store in the variable.

Radio Buttons and Multiple-Choice Questions

If you have multiple-choice questions, you might not want separate buttons for them; instead you might want to use radio buttons. These are a special kind of button that allows you to click on one and only one answer. When you click an answer, the button is filled in, and the other buttons are cleared. You can get radio buttons by using an INPUT of the type "radio." There are two tricks to radio buttons. First, they are just little circles--no text. Thus, if you want them labeled, you have to put some text next to them (I like to use HTML table tags for this). Second, to make sure that all the buttons in one section are linked together, they must have the same name (that's the name= in the INPUT tag). For example, you might have:

<INPUT type="radio" name="myRadioThing"> First Choice
<INPUT type="radio" name="myRadioThing"> Second Choice

That is the basic format. The complexity of everything in the following example, is due to the table to get everything lined up properly.

Additionally, when a radio button is clicked, you might want it to run a script. You could have a click on a button give feedback immediately (running our earlier RightAnswer or WrongAnswer function), but usually radio buttons allow you to change your mind, and wait until you click another button to submit your answer. That is where our variable comes in. We'll have a variable:

var correct;

that will be true if the correct answer is chosen and false if the incorrect answer is chosen. This will change every time a radio button is pressed, but it will not say anything. Thus, our radio buttons, need:

onclick="RightAnswer"

or

onclick="WrongAnswer"

To run a new RightAnswer or WrongAnswer function:

function RightAnswer()
{
correct = true;
}
function WrongAnswer()
{
correct = false;
}

These are just used (along with the correct variable) to decide if the last chosen answer is right or wrong.

Finally, we need to have a button that checks the answer and gives feedback using the following script:

function CheckAnswer()
{
if (correct == true)
{
alert("Good job")
}
else
{
alert("Try again")
}
}

This simply asks if correct is true. If it is, "Good job." Otherwise, "Try again."

Now, you have all the parts, so let's put it all together in one file (click here to see the file):

<HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--
var correct;
function RightAnswer()
{
correct = true;
}
function WrongAnswer()
{
correct = false;
}
function CheckAnswer()
{
if (correct == true)
{
alert("Good job")
}
else
{
alert("Try again")
}
}
-->
</SCRIPT>
</HEAD>
<BODY>
<FORM name="radioForm">
<TABLE border=0>
<TR><TD colspan=2>What is the capital of Maryland?</td></tr>
<TR>
<TD align="right">
<INPUT type="radio" name="capital" onClick="RightAnswer()">
</TD>
<TD>Annapolis</TD>
</TR>
<TR>
<TD align="right">
<INPUT type="radio" name="capital" onClick="WrongAnswer()">
</TD>
<TD>Baltimore</TD>
</TR>
<TR>
<TD align="right">
<INPUT type="radio" name="capital" onClick="WrongAnswer()">
</TD>
<TD>Bel&nbsp;Air</TD>
</TR>
<TR>
<TD colspan=2>
<INPUT type="button" name="check" value="Check Answer" onClick="CheckAnswer()">
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>

Wrapping Up

This is just the beginning of what you can do with JavaScript. Hopefully, it will get you started. You can always find scripts on the Web that do what you want and try to copy them and adjust them for your own purposes, or you can try to write your own.


This page was prepared by: David M. Marcovitz, Ph.D.

Last updated: July 21, 2008

Loyola College Education Department

[Loyola College | Education Department]