Free Javascript Tutorials

home

JavaScript Tutorials

Functions

 
Our quick javascript links
Little Programmes
 
 
 
 
 
 

 

JavaScript Functions

 


We've already used functions a fair bit in these pages. We're going to explore them a bit further. Functions, if you remember, are simply sectioned-off pieces of code. When you want to use your code segment, call it by its name and it will come running.

We're now going to design a little calculator. It's limited in what it can do, as it only calculates two numbers at a time. It can add, divide, multiply and subtract. To save you time designing the HTML for this calculator, you can get a copy by clicking the link below. When the web page opens, click File > Save and save it to your hard drive.

Click here for the HTML code


Nice, isn't it? Only the HTML is included in the code for the web page. All the script tags have been taken out, so it won't work. But we'll see how functions work with this calculator. Off we go then.

To work the calculator, press a number. Then press an operator (plus, times, subtract, or divide). Press another number, then press the equals button (=). If you want to clear the display, click the cls button.

 

Passing a value to a function

So far with functions, we have just been doing this sort of thing:

function add() {
Our code segment here
}

The name of the function is add. Immediately following the name are a pair of round brackets ( ). To call (use) our functions, we've doing this:

<Input Type = button onClick = add()>

Inside the round brackets, we haven't put anything. They have been empty brackets. But functions are given extra power by putting something inside the brackets. This "something" is called an argument. An argument is really just a variable. What you're doing by giving your function an argument is passing a value to your function. We're going to do that with our calculator.

Our first function will accept one argument. The value being passed to our function comes from the number buttons on our calculator. If you have a look at the HTML calculator code in the page you saved, you'll see this for the buttons:

<Input type = button name = b1 value = " 3 " onClick =calculate(3)>

The value above is the text on the button face. This is the number three button. When this is clicked, the number three will appear in the display. Look at the onClick event:

onClick =calculate(3)

The onClick event is calling our function, which has the name calculate(). However, we've now put something inside of the round brackets. We've put the number three in there, which is the value of our button. Here's the function we're going to add, minus any code:

function calculate(number) {

}

Our function now accepts an argument - number. This is a variable into which we can place values. When the 3 button is clicked on the calculator, a value of 3 will be placed into the number variable. If another button is clicked, the 7 button for example, a value of 7 will be passed to the number variable. We can then use this number variable in our code for the function:

function calculate(number) {
frm = document.frmOne.txtDisplay
frm.value = frm.value + number
}

You should be able to work out what the code for the function does, but here's an explanation. The Display textbox is first put into a variable called frm. We then add whatever is in the variable number (our argument) to whatever is already in the display text box. Here, add means "join together". So if you wanted 22 in the Display text box you would click the 2 button twice.

This is a nice, simple function that display numbers in a text box. You can add the function to your calculator. Either type or copy and paste the function into the HEAD section of your code.

OK, now that we know how to pass a value to a function, we can set up a second function to deal with the operators. When you click one of the operator buttons (plus, minus, etc) you can pass the operator to a new function in the same way you've just done. First, set up the onClick event in the HTML form (this has already been done):

<Input Type = Button value = " plus " onClick = operator("+")>

Notice the name of our new function, and the value we are going to pass to it when the "plus" button is clicked:

onClick = operator("+")

What we're passing to our new function is the plus symbol ( + ). We're passing it as a string, hence the double quotes surrounding it. For the divide button, we have this for the onClick event:

onClick = operator("/")

In other words, a different symbol will be passed to our new function depending on which operator button is clicked. Here's the code for the function:

function operator(opval) {
TheOperator = opval
total = document.frmOne.txtDisplay.value
document.frmOne.txtDisplay.value = ""
}

This time, the variable inside our function is called opval. This is our argument. When an operator button is clicked, opval will contain one of our four symbols. Inside the function we then pass this value to a variable which we have called TheOperator. Besides passing the operator symbol to a variable, this function also gets the value from the display and passes it to a variable called total. The text box is then cleared ready for another number to be entered.

So add this new function to your script, just below the first one. However, the variables total and TheOperator need to have their values read from another function. So we have to make them global. We do this by declaring them at the top of the code, just before the first function:

<SCRIPT Language = JavaScript>

var total = 0
var TheOperator = 0

function calculate(number) {
frm = document.frmOne.txtDisplay
frm.value = frm.value + number
}

function operator(opval) {
TheOperator = opval
total = document.frmOne.txtDisplay.value
document.frmOne.txtDisplay.value = ""
}

</SCRIPT>

With our two global variables set up, we can now do the calculating part. The calculating is done when the equals sign is clicked on the calculator. Again, we do this with an onClick event. This time from the equals button on the form:

<Input Type = Button value = " = " onClick = equals()>

We don't need to pass anything to our equals function (it's a simple little code segment), so we're back to the empty round brackets. This means that it's a function that doesn't accept arguments. Here's the entire function that does the calculating:

function equals() {

CurentDisplayValue = eval(document.frmOne.txtDisplay.value)
PreviousDisplayValue = eval(total)

if(TheOperator =="+") {
answer = PreviousDisplayValue + CurentDisplayValue
}
else if(TheOperator == "*") {
answer = PreviousDisplayValue * CurentDisplayValue
}
else if(TheOperator == "-") {
answer = PreviousDisplayValue - CurentDisplayValue
}
else if(TheOperator == "/") {
answer = PreviousDisplayValue / CurentDisplayValue
}
document.frmOne.txtDisplay.value = answer
}

The code looks a tad messy, but that because of the variable names we've chosen to use. First, we pass whatever is currently in the Display text box to a variable called CurentDisplaValue:

CurentDisplayValue = eval(document.frmOne.txtDisplay.value)

The eval() part just ensures that JavaScript doesn't try to concatenate when we want to add up. The second line of our code gets the value stored in our global variable total and passes it to the new variable called PreviousDisplayValue:

PreviousDisplayValue = eval(total)

The rest of the code just uses if statements to check what is inside our other global variable TheOperator. The final line just pops the answer into the Display text box.

And that's it. A very simple calculator that demonstrates how to pass values to functions by setting up arguments. You can pass more than one argument at a time to a function. But we've kept things simple by using only one argument with each function.

Add the new code to your calculator and see it in action. When you get it working, it should be like the one in this link below:

See the Working Calculator

In the next part, we'll see how to use functions to validate data on a form.

Move on to the Next Part-->

<--Back to the JavaScript Contents Page