As we've seen from reading Chapter 19, programmers use functions in programming and scripting languages to reduce complexity and to effectively and efficiently reuse code. By understanding how functions work and learning how to make our own functions, we can begin creating more advanced programs and scripts.
In this nineteenth lab, you'll build a function to calculate your grade point average, or GPA. As you explore, review your answers from the To consider: section above. Have you changed your mind about any of them?
Let's review the three parts required for building a function:
Can you see why we're calling it "building" a function? Functions are built using blocks of code, just like programs are built using blocks of code like functions.
Before we dig in to creating our own functions, let's take some time to test out functions in a sandbox environment. w3schools has many editable demonstrations of JavaScript functions. Here's a demo that uses one function with two different results based on the arguments passed in to the function when it is called.
Date()
function to also get today's
the date to display in the alert box. you should get an alert that looks
something like the image below. Does the date display for every button? Test it.Try IT: My GPA Calculator
Let's start by reusing a file we have already created that has a good
skeleton for adding scripts. Open the lab17start.txt
file, and save it as mygpa.html. Edit the file to replace the <title>
and <h1> tags that mention My Astrologer with a title and heading of your choice.
Now that we have the framework, it's time to think about what exactly we want our GPA calculator to do. It should be able to:
Since we want to use a form for entry, like the BMI Calculator from Chapter 19, we will need to create not only our script with the function, we will also need to create the form. Add the opening and closing <form> tags to your skeleton, after the <script> tags. You should now have code that looks something like this:
Time to start building the function. What should our inputs be?
We know we have five classes, with five grades. The function needs
to take all of those grades in as parameters. Inside the <script>
tags, write your function. Even though the grade values change, we don't need
to define them as variables because they will be local to
the function. The names we use as parameters will be the names we use
inside the function to perform the calculation. Write a statement
to perform the algorithm for calculating the average. Next write a
return statement to get the calculated value back out of the
function, and close the curly braces. To test this function, use
alert() in a statement directly after the function to pass
in arguments to the function and display them in an alert box. That
statement may look something like this:
alert("My GPA is " + gpaCalc(1.0, 2.0, 3.0, 4.0, 2.0));
with this alert:
Once we have tested our function to make sure it works, we can remove the alert box, and move on to building the form.
Like the BMI Calculator, we'll use <p> tags to enclose
our instruction text and our text entry fields. And, like the BMI Calculator,
we'll use the onchange event in our last input field to change
the value in our results field. An important note:
sometimes getting the .value of a text field will return a string
and not a numeric value. One way to make sure we send numeric values to our function
is to wrap the values we get from the text fields in a built-in
JavaScript function called parseFloat() that will keep the decimal
format of the grades we enter. A sample statement that uses this function
looks like this:
parseFloat(document.forms[0].gradeone.value)
Reading from inside the parentheses outward, this statement is getting
the string value from the text field called "gradeone", then
converting it back to the decimal value using parseFloat. If you keep the
values as strings, they will be concatenated with the
"+" operator, and not added - which can make your GPA look really off!
Can you think of other ways to make sure the function gets numeric values?
So what does our code look like so far?
<script language="javascript">
function gpaCalc (g1, g2, g3, g4, g5) { //take in 5 grade values
var myGPA = (g1+g2+g3+g4+g5)/5; //get their average
return (myGPA).toFixed(2); //return the value to 2 decimal places
}
</script>
<form action ="">
<p>Enter the grade for your first class:
<input type="text" name="gradeone" size="4" /></p>
<p>For your second class:
<input type="text" name="gradetwo" size="4" /></p>
<p>For your third class:
<input type="text" name="gradethree" size="4" /></p>
<p>For your fourth class:
<input type="text" name="gradefour" size="4" /></p>
<p>For your fifth class:
<input type="text" name="gradefive" size="4"
onchange="document.forms[0].gpa.value=
gpaCalc(parseFloat(document.forms[0].gradeone.value), //use parseFloat to make sure our function gets numerical values
parseFloat(document.forms[0].gradetwo.value),
parseFloat(document.forms[0].gradethree.value),
parseFloat(document.forms[0].gradefour.value),
parseFloat(document.forms[0].gradefive.value))" /></p>
<p>Your GPA is:
<input type="text" name="gpa" size="4" /></p>
</form>
Your webpage with the script and form inside will probably look something like this:
What's left to do? We need to add some <style> tags in
the <head> section of our page to make our form look nicer. We also need to change
the result from a change in a text box to a button called "Submit Grades"
that will use its onclick
event to display an alert box with our current GPA and a message based on
the value. We can use if statements like we did in
Lab 17 to show the correct message for the GPA range. If you need a working
version of the script to get started, you can download the
Lab 19 script text file, then save it with an .html extension. Remember, you can use
a browser plugin like Firebug to help you with this, or use alert()
to show you the values of variables as they get set or changed. Check your
work against the completed version, Lab 19:
Completed Script.
Now that you've built a function and linked it to a form, you're ready to move on to more advanced programming concepts. In Lab 20, we'll learn about tools like the for loop and arrays that can help us simplify our programs even more.