Tutorial 7: JavaScript forms - Candy Store 2

advertisement
CMPT 100 : INTRODUCTION TO
COMPUTING
#7 : JAVASCRIPT AND
FORM TUTORIAL - CANDY STORE 2
TUTORIAL
1
By Wendy Sharpe
BEFORE WE GET STARTED
...
Log onto the lab computer (in Windows)
 Create a folder for this tutorial on H:// drive
 Log onto Moodle and open tutorial 7 notes


You have two options for the html form:
Use the form you created from last week (might have
errors)
 Click on candystore.html link in the tutorial notes and save
to your newly created folder


Open Notepad++
Start – All Programs – Course Specific Applications –
Notepad+++
 DO NOT OPEN THE SAME FILE WITH
KOMPOZER AND NOTEPAD++ AT THE SAME
TIME

2
TUTORIAL

Creating/calling functions and creating variables


7 OVERVIEW
Using the onClick event handler
Accessing and processing information from a
form
text fields
 radio buttons
 error checking numerical values

Putting information back into a form
 Printing a receipt with a second function
 Debugging JavaScript
 Where you can get help with Assignment 4 or the
additional exercises in Tutorial 7

3
TUTORIAL

7 PUBLIC SERVICE ANNOUNCEMENT
this tutorial has the potential to be very “buggy” if
you don’t keep track of
variable names
 function names
 syntax of built-in functions that you call to get information
from a form
 id of text fields
 names of groups of radio buttons
 step outside the array that stores radio buttons (more on
that later)
 if you’re killing a loop/if early by terminating it with a
semi colon
Use syntax higlighting and your error console as much as
you can.
4

CREATING/CALLING FUNCTIONS
AND CREATING VARIABLES
5
ADDING THE SCRIPT TAGS
Functions can be defined both in the <head> and
in the <body> section
 So how do you know where to put the script?

to assure that a function is read/loaded by the
browser before it is called, put functions in the
<head> section
 We’re putting our script in the <head> of the
candystore document form

6
CREATING YOUR VARIABLES

The number of variables you want to create
depends on how much you want to break down
the information for each piece of data

I.e., you have information for gummy bears, jelly
beans, packaging, delivery, name, and total cost


E.g., gummy bears has a number of gbears selected by the
user, and a price associated with them. You’ll want to
create two variables to ‘remember’ this information.
create variables inside of your <script></script>
tags but OUTSIDE of your functions.

Why? Because global variables can be used by all
functions in your script.
7
CREATING YOUR VARIABLES PART DEUX

Don’t forget to initialize your variables . . .
especially the ones that are going to hold strings

My program’s variables:
var gbears = 0;
var gbearsCost = 0;
var jbeans = 0;
var jbeansCost = 0;
var deliverytype = "";
var deliverycost = 0;
var packagetype = "";
var packagecost = 0;
var name = "";
var totalcost = 0;
8
FUNCTION SYNTAX

We’ve used functions before . . . but someone else
has made them for us


remember JavaScript’s Math class functions?
Basic function syntax
function functionname(var1,var2,...,varX)
{
the code you want to execute
}
 function functionname()
{
the code you want to execute
}
 the difference is in the arguments to the function
 Go ahead and create your order() function, put an
alert inside the function that says “hello” to prove to
yourself that the function does something.

9
CALLING THE ORDER() FUNCTION


We’re using the onclick event to call functions for
our form
onclick is an event that occurs when the user clicks
a button on your form

general syntax


onclick="SomeJavaScriptCode”
Add an onclick event to your “Order Now” button
This is what your button looks like in code
<input name="submitButton" value="Submit!" type="button”/>
 Your onclick event will go at the end of the button code
<input name="submitButton" value="Submit!" type="button”
onclick goes here/>

10
WE’VE GOT A FUNCTION
. . . NOW
WHAT?
A.K.A. ACCESSING INFORMATION IN
THE FORM
A. ACCESSING TEXT FIELDS
B. RADIO BUTTONS
11
A. ACCESSING TEXT FIELDS
12
ACCESSING GUMMY BEAR DATA
:
GetElementById()

How will you grab the number of gummy bears
entered by the user into your form?
using the document.getElementById built-in function
 the Id part of it refers to the id that you had assigned to
your form text fields last week:

<input id="gummyBears" name="gummyBears" value="0" />
 If you have forgotten how to set up this id, go back to last week’s
tutorial (Tutorial 6)


For more info on how to use:
http://www.w3schools.com/jsref/met_doc_getelementbyid.a
sp
General syntax:

myFormVariable = document.getElementById("id")
13
ACCESSING GUMMY BEAR DATA
:
getElementById()

getElementById will return a string to your variable
so you will have to use parseInt
parseInt takes a string argument and returns a number
 For more info on parseInt:
http://www.w3schools.com/jsref/jsref_parseint.asp

// get number of gummybears
gbears = parseInt(document.getElementById("gummyBears").value);

You can check and see if you’ve accessed the
information in the correct way by using a debugging
statement

specific ways of using alerts to track down issues in your
program and verify that you’re doing things correctly.
14
ACCESSING THE JELLY BEAN DATA

access the same way as the gummy bear data
15
ERROR CHECKING FOR NUMERICAL VALUES

parseInt will parse whatever you give it

you can check to see if the user enters a non-numerical
value by using the isNaN funtion

NaN == Not-a-Number
if(!isNaN(gbears))
{
//if yes - calculate cost of gummybears
gbearsCost = gbears*10;
// alert("Number of gbears: " + gbears);
}
else
{
//if no - print error message
alert("Error! Please enter a numeric value for Gummybears!");
}
16
CUSTOMER NAME

you’re on your own for creating the code to get
the customer’s name from the form
17
B. ACCESSING RADIO BUTTONS
18
RADIO BUTTONS

your radio buttons all must have the same name to be a
part of the same group

I.e., our packaging types have the same name
<input checked="checked" name="containerType" value="2"
type="radio" />Gift Bag ($2)<br />
<input name="containerType" value="3" type="radio" />Decorated Can
($3)<br />
<input name="containerType" value="0" type="radio" />Box (Free!)

JavaScript stores the value of the group of radio
buttons in a special type of variable called an array
an array holds data of the same type (like a containerType)
 we step through arrays with a single for-loop


arrays start at 0
19
FOR LOOP TO ACCESS THE DELIVERY
for (var j=0; j<=1; j++)
{
//for each radio button in DeliveryType - see if checked
if(document.getElementsByName('deliveryType')[j].checked)
{
//if yes - get cost of delivery
deliverycost = parseInt(document.getElementsByName('deliveryType')[j].value);
//determine which is checked to get ype
if(i==0)
{
deliverytype = "Canada Post";
}
else
{
deliverytype = "FedEx”;
}
}
}
20
ACCESSING RADIO BUTTON DATA WITH
getElementsByName()

grabbing the data for a radio button is slightly
different than with the text button
parseInt(document.getElementsByName('deliveryType')[j].value)



radio buttons don’t have an id like a text box,
they have a name
so, in order to access them, we need to get the
elements of a group of radio buttons by their
name
your turn: add a for-loop to access the contents of the
container/packaging data
21
PUTTING DATA BACK INTO THE
FORM
22
TOTAL COST
we need to tell the user the total cost of the purchase
 Total cost is a form text field . . . it’s like how we
accessed the jelly bean/gummy bear data but in reverse


add up all the cost variables for each item purchased, put it
into your total variable
I.e.,
totalcost = gbearsCost + jbeansCost + packagecost + deliverycost;


assign the value of the total variable back into the element
of the form with the id ‘totalCost’
formdocument.getElementById('totalCost').value = totalcost;

now, display an alert thanking the customer for their
purchase and we’re all done with the order() function
23
PRINTING A RECEIPT WITH A
SECOND FUNCTION
24
CREATING THE SECOND FUNCTION

You a way of telling the program to print a receipt
when a button is clicked
<input name="printReceipt" value="Print Receipt!" type="button"
onclick="printrec()"/>

Create a second function AFTER the order() function
why?
 order of your code is important. We’re going to call the
order() function from our receipt printing function
 if the receipt printing function is put before the order()
function it won’t actually know what the order() function
is
 computers aren’t smart, they do what you tell them to do .
. . in order

25
PRINTREC() FUNCTION
function printrec()
{
order();
document.write("<h1>Your Receipt</h1>");
// other stuff goes in here . . . I’ll let you fill it in
document.write("Customer Name: "+ name);
}
26
DEBUGGING JAVASCRIPT
27
SCRIPT NOT WORKING?

Common places to look for errors






Did you spell variables correctly?
Is your code in order? Are you trying to use variables
before they have a value associated with them
American English spelling of words like color
Are all semi-colons where they need to be?
Use syntax highlighting to find errors
Did you concatenate your strings properly?
+ in the right places
 Proper use of double quotation marks


Using the error console in Firefox to find
problems with your script

Tools – Error Console


Tip: clear the error console, then force refresh
Errors option will give you information about what
line of code has the problem
28
WHERE YOU CAN GET HELP WITH
ASSIGNMENT 4 OR THE ADDITIONAL
EXERCISES IN TUTORIAL 7
29
GETTING HELP

Your instructor (free...well...cost of tuition)


can help clarify assignment guidelines, requirements,
marking scheme, and can generally help you debug
Computer Science Help Desk (free)
in the little room between the open Mac lab and the
big open dual-boot Spinks lab
 there’s a lab advisor schedule on the wall
 if someone is scheduled but not physically present,
write your computer name (located on the label on
the box) on the whiteboard


CS Tutors ($$)


https://wiki.usask.ca/display/csss/CSSS+Tutor+List
Online
specifically www.w3schools.com
 http://www.w3schools.com/js/default.asp

30
QUESTIONS?
31
Download