310 likes | 523 Views
CMPT 100 : introduction to computing tutorial #7 : javascript and form tutorial - candy store 2. 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
E N D
CMPT 100 : introduction to computingtutorial #7 : javascript and form tutorial - candy store 2 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 oncandystore.htmllink 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
tutorial 7 overview • Creating/calling functions and creating variables • 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
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.
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
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.
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: vargbears = 0; vargbearsCost = 0; varjbeans = 0; varjbeansCost = 0; vardeliverytype = ""; vardeliverycost = 0; varpackagetype = ""; varpackagecost = 0; var name = ""; vartotalcost = 0;
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.
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/>
we’ve got a function . . . now what?a.k.a. accessing information in the form a. accessing text fields b. radio buttons
accessing gummy bear data : getelementbyid() • How will you grab the number of gummy bears entered by the user into your form? • using thedocument.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.asp • General syntax: • myFormVariable = document.getElementById("id")
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.
accessing the jelly bean data • access the same way as the gummy bear data
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 isNaNfuntion • 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!"); }
customer name • you’re on your own for creating the code to get the customer’s name from the form
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
for loop to access the delivery for (varj=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”; } } }
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
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
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
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); }
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
Where you can get help with Assignment 4 or the additional exercises in Tutorial 7
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