by Richie Lai
First published: April 1999
The idea behind So let's get rolling...
General Information Now that you know where to put scripts, what can you do with them? First of all, let's get a few things straight.
- Variables are CaSe SeNsItIve. Make sure you keep this in mind.
- There are no type casted variables. Something that is a string can also be an integer.
- Learn your object model. The hierarchy of the object model must be understood in order to manipulate objects in your HTML page.
- There is more than one way to do everything, with no set right or wrong way.
Our First Script Now for our first script! Let's create something that will cover a few things at once: a calculator that will add two numbers inputted by a user. Basically, we're going to take a form with two input fields and add them together, then show a message box with the answer. Sound simple? It is. Let's look at the code first, and then we'll go through and figure out what we did.
x = eval(document.AddForm1.Value1.value) + eval(document.AddForm1.Value2.value);
<INPUT TYPE="text" NAME="Value1" SIZE="3"> +
<INPUT TYPE="text" name="Value2" SIZE="3">
<INPUT TYPE="button" onClick="AddNumbers()" VALUE="Answer!">
There are two important things to notice here. The first is the way we get the values; to reference the first number we have to grab it from the form.
|-- Second tier name.. in this case,
the name of the form
|-----| Third tier name... in this
case, the name of the text input
| Finally, value is
the keyword used to get a value
from the form
Now that we know that we should be able to reference anything in this form. It's very important to keep the names and cases of your fields straight, else this will fail.
The next thing you notice here is the
eval(). eval basically evaluates what you pass to it. In this case, since we don't know what kind of variables we are getting, we want to evaluate each value--we are getting the integer value and then adding. If we were to omit the
eval()s, we would get
Value1Value2 in the alert box since it would concanate the values together.
Of course, there is more than one way to do everything. This same script could have been inside another, only with parameters. Let's look at another way of doing this.
<INPUT TYPE=TEXT NAME="Value1" SIZE=3> +
<INPUT TYPE=TEXT NAME="Value2" SIZE=3>
<INPUT TYPE=BUTTON ONCLICK="AddNumber2(this.form.Value1.value,this.form.Value2.value)" VALUE="Answer!">
The principle is exactly the same, but as you can see, design is different. Doing this adds no advantage, but later, as we go into more complex scripts, you will see that passing parameters is a huge advantage to hardcoding. Now that we've established the basics, let's move on...
Part 2 > ]