Presentation is loading. Please wait.

Presentation is loading. Please wait.

IT 130 – Internet and the Web - Yosef Mendelsohn

Similar presentations


Presentation on theme: "IT 130 – Internet and the Web - Yosef Mendelsohn"— Presentation transcript:

1 IT 130 – Internet and the Web - Yosef Mendelsohn
JavaScript contd: Scope, Built-in functions, Precedence, If-statements

2 Fair Warning: Several of the concepts from the next two Javascript lectures will be well-covered on your final exam. You can expect at least one question on each of: scope built-in functions in general parseInt() function precedence if-else will be extensively covered between now and the end of the course. 2

3 New topic: Built-In Functions
In addition to the functions we have been creating ourselves, JS has many built-in functions. Some of them are quite useful. In fact, document.write() is one such built-in function. It takes whatever the programmer puts inside the parentheses and outputs the result to an HTML document. Another convenient JS function is alert() . This works similarly to a document.write function, except that the output goes to a dialog box instead of an HTML page.

4 Some Predefined Functions
We have already created many functions. However the JS language has many built-in functions that we can use. document.write() alert() Math.sqrt() Math.floor() Date() parseInt() prompt() //use ONLY during testing 4

5 Some of these predefined functions in use:
var number, rollDice, todaysDate; number = Math.sqrt(25); rollDice = (Math.random()*6) +1; //Generates a random number between 1 and 6 //More on this later todaysDate = Date(); //generates the date and time based //on the computer’s clock alert("The date is:" + todaysDate); 5

6 The alert()function A built-in JS function
Works similarly to the document.write function, except that the output goes to a dialog box instead of an HTML page. Because the output does not write to an HTML page, you can NOT use HTML markup. I.e. Only text can be outputted to an alert dialog box. The most common usage of the alert() box is to give the user an error message such as entering incorrect information in a form. e.g. alert(“You must enter your birthdate as MMDDYY”); It is VERY convenient for testing purposes. Rather than have to write out an entire document.write statement, you can simply output a quick ‘alert’ function

7 The alert() function in action:
<script type=“text/javascript"> var age=30; alert("You are" + age + " years old."); </script> Will display the following alert box:

8 The alert() function alert("testing an alert box"); var x=5; alert(x); var age=30; alert("You are " + age + " years old."); A “quick and easy” way of outputting information – particularly useful for testing purposes.

9 Quick review: the + operator
Recall how the ‘+’ operator works differently depending on the data types: "foo" + "bar"  "foobar“ (two strings, therefore, concatenation) "5" + "6"  "56“ (also two strings, therefore, concatenation) 5 + 6  11 (two numbers, therefore addition) What about the following? "5" + 6  "56" 6 + "foo"  "6foo“ In other words, if you try to add a string to anything including numbers, the ultimate result will be a string.

10 ** Built-in functions contd: parseInt()
Recall that when you retrieve the value from a textbox, the value is considered to be a “string” of TEXT. That is, the value is NOT a number. Consider the following: var age = document.form1.txtAge.value; //eg: 25 var ageNextYear = age+1; The value of ageNextYear will be set to !!! The reason for this strange behavior is that the ‘+’ operator is placed between TEXT (“25”) and an INTEGER (1). In this case, you do NOT get addition! You get concatenation.

11 ** Key Point: Whenever you read in a value from a form and wish that value to be treated as a NUMBER, you should invoke the (highly useful) built-in JS function called: parseInt() Here is one way of doing that: var age = document.form1.txtAge.value; age = parseInt(age); //age can now be treated as a regular number Note that parseInt() will work ONLY if the value from the form contains nothing other than DIGITS. One period is okay too. If there are any other characters such as commas, quotes, letters, symbols, etc, this will likely cause your script to malfunction. FROM NOW ON, whenever you read in a quantity from your web form, you MUST invoke the parseInt() function on that number. The grader will deduct points every time you forget to do so! 

12 *** The Math.random()function:
The following line of code: (Math.random()*25) +1; Will generate a random number between 1 and 25 You can replace the number 25 with any other number you like Will give back a numeric value with integers. The parseInt function below will remove (“truncate”) all of the numbers after the decimal. E.g will be converted to just 23. You will use this function many times between now and the end of the quarter. Math.random and parseInt in action: var random = (Math.random()*10)+1; random = parseInt(random); //remove the decimal numbers (later) alert("A random number between 1 and 10: “ + random);

13 * Another use for parseInt()
parseInt() also is useful for removing decimal values Recall that Math.random() returns a number that has decimal spaces. Frequently, however, we simply want an integer. We can use parseInt() to remove the decimals: var random = (Math.random()*10)+1; random = parseInt(random); //remove the decimal numbers alert("A random number between 1 and 10: “ + random);

14 ** Built-in functions contd: parseFloat()
Recall that parseInt chops off all decimal values. If you want to KEEP decimals, you must use parseFloat() var length = document.form1.txtLength.value; //eg: length = parseFloat(length);

15 ** Using parseInt and parseFloat
From now on you MUST use parseInt() or parseFloat() – but ONLY where appropriate. Whenever reading in a numeric quantity from a form (e.g. age, weight, amount, etc), use them. If you are not reading in a quantity (e.g. a name, city, etc), do NOT use them.

16 Scope The scope of a variable is the part of the program where the variable can be used / accessed / referenced. There are two types of variables: local and global. 16

17 Scope A local variable is declared in a function. Its scope is within the function where it is declared. In other words, it can be used only within that function. A global variable is used between script tags in the body of the web page. Its scope is within the entire web page. In other words, it can be used throughout the entire current document (although, only inside Javascripts). However, global variables can be problematic at time, and are RARELY EVER USED!! In fact, we will NOT be using global variables in this course. 17

18 Local Variables All variables declared in a function are local variables: they do not exist outside that function. Although local variables may seem restricted, they are very useful and are used constantly in programming. 18

19 Scope contd What is the scope of ‘x’ in this code?
<script> function f1() { var x; x = 3; document.write(x); } Answer: the function ‘f1’

20 Scope contd Are there any problems with this code?
<script> function f1() { var x; x = 3; document.write(x); } function f2() x=5; </script> Answer: the variable ‘x’ inside function ‘f2’ is undeclared. ‘f2’ has no idea that the variable x exists elsewhere.

21 Where should you put your variables?
It’s okay to have variables anywhere, but remember, you can not use a variable until you declare it. Generally, we try to group all variables we plan on using, together at the top of the function.

22 Rules of Precedence a = 5; b = 20; result = a + b / 5 - 1; What value is of ‘result’? answer = b+2 / 2; What is the value is ‘answer’? (Assume that the variables were declared earlier in the script)

23 Operator Precedence Multiplication and division have higher precedence (they are evaluated before) than addition and subtraction. Operations with the same precedence are evaluated left to right. IMPORTANT: You can use parentheses to force the evaluation order: the innermost ( ) are evaluated first. If you have any doubt when writing an expression, use parentheses.

24 Precedence practice: What is the order of operations for formulas below? var a, b, position, result; a = 5; b = 20; result = a + b / 2 - 1; Answer: b/2  add to a  subtract 1 (=14) position = a * 5 + b / 10; Answer: a * 5  then b/10  then add the two (=27)

25 Precedence example: To convert a temperature from fahrenheit to celcius you must subtract 32, then multiply by 5 and divide over 9. var celsius, far; far = 100; celsius = far - 32 * 5 / 9; //WRONG!!! (Will first do 32*5, then divide by 9, then subtract the total from far) celsius = (far-32) * 5 / 9; // RIGHT! // Anything inside parentheses gets carried out // *first*

26 Practice: Create a form that asks the user for a temperature in farheheit. One text box for the temperature One button to submit the form Write a function that outputs the result in celsius. Output inside an alert box. That is, instead of document.write(…), use alert(….); Formula: To convert a temperature from fahrenheit to celsius you must subtract 32, then multiply by 5 and divide over 9

27 The assignment operator: ‘ = ‘
First the entire right side of the ‘=‘ is evaluated e.g. a mathematical formula e.g. retreiving the value from a form Then the result is stored in the variable on the left. E.g. celsius = (far-32) * 5 / 9; age = document.formName.elementName.value;

28 Example: x = x + 1 We can add or subtract from the current value of a variable using the example above. If this line of code seems confusing, recall how the assignment operator works (i.e. right-side first  then assignment). x = 5; x = x + 1; alert(x); What’s the value of ‘x’? Again, recall that everything on the right side of the assignment operator (‘=‘) is carried out first. Then the assignment is done. So in this case, x will be set to 6.

29 Other error values you may encounter
NaN Not a number var x = “hello”; x = x * 5; //will generate the ‘NaN’ error // Try it! Infinity Infinity (e.g. 4 / 0) In JavaScript, 4/0 equals “Infinity”. But in mathematics, 4/0 is undefined, which means it has no value.

30 *** CONDITIONALS: “If…”
Types of Conditional statements if statement if-else statement Nested if statements Boolean expressions 30

31 Example usages: if due date on book is before today’s date
charge overdue fee if day of the week is not Sunday or holiday parking meter must be used if number of hours worked is more than 40 pay overtime 31

32 Types of program execution:
program step 1 program step 2 program step 3 program step 4 program step 5 Unconditional execution (i.e. no conditionals present) the JavaScript interpreter executes each line in sequence Conditional execution (a conditional IS present) evaluate a condition execute code only if condition is true i.e. the code is not always executed might be a block (several statements) of code controlled by the condition condition conditional step(s) program step 2 program step 3 program step 4 32

33 Syntax: The if statement
if (condition) { statements } 33

34 Using braces for ‘if’ statements:
If your ‘if’ statement has only one line of code, the braces are optional. if (condition) { statement 1 statement 2 } statement In general, I recommend that you ALWAYS use braces until you become very comfortable with this technique. In fact, I’m only showing you the version without braces in case you see it elsewhere. more than one statement – braces are required one statement only – braces are optional 34

35 The ‘if’ statement (without ‘else’)
Conditional execution evaluate a condition execute the set of statements if condition is true do not execute the statements if the condition is false if (condition) conditional true code program step 2 program step 3 program step 4 program step 1 35

36 Example if (dateToday > dueDate) { 1. calculate fine
2. overde notice } 36

37 Curly braces { } are called curly braces or braces.
You want to format (e.g. indent) if statements and if-else statements to make your code easier to read by you and by others (colleagues, the grader!, etc). 37

38 Braces Write them like this: { } ... body ...
if (condition) { ... body ... } Note how the braces are on separate lines (just as we have been doing with functions). 38

39 White space is your friend
The JavaScript interpreter ignores white space (blank spaces, blank lines, tabs). So, for example, you could write an entire block of code such as an if-statement on one single line: if (condition){ line 1; line 2; line 3; ... } But of course this makes the code harder to read and understand. 39

40 Example: Prompt the user for the number of hours they worked. If the hours are over 40, print: “Wow, a hard worker!” Because we are just testing/practicing, it’s okay to use the prompt function to get input from the user Remember, that in the real world, we read input from a form Use document.write to output var hours; hours = document.form.txtHours.value; hours = parseInt(hours); if (hours > 40) { document.write("Wow, a hard worker!"); }

41 Practice: Prompt the user for their age. If their age is 18 or more, print: “You can rent a car!” var age; age = document.form.txtAge.value; age = parseInt(age); if (age >= 18) { document.write("You can rent a car!"); }

42 * The >= operator: This is a way of saying “equal or greater to”.
In the last example, the conditional: age >= 18 is a way of saying: if the user is equal or greater than 18… You can also use <= to indicate less than or equal to.

43 Practice: Prompt the user for the day of the week. If it’s a Sunday, print: “No need to pay the meter!” var day; day = document.form.txtDay.value; if (day == "Sunday") { document.write("No need to pay the meter!"); } ***** Note the comparison operator ‘ == ‘ . If you want to compare two values, you need to use ‘==‘. Using one equals sign ‘=‘ will NOT work. I’ll explain more about this shortly.

44 The if-else statement Conditional execution evaluate a condition
execute one set of statements if condition is true execute the other set of statements if condition is false if (condition) conditional true code else condition false code program step 2 program step 3 program step 4 program step 1 44

45 Example var age; age = document.form1.txtAge.value;
age = parseInt(age); if (age >= 18) { alert("You can rent a car!"); } else alert("Go find a bike."); 45

46 Practice: Download ‘basic_form.htm’ (see week 4) and modify it to do the following: Ask the user how many hours theyworked in the last week. If they worked more than 40 hours, output “Wow, a hard worker” , if not, output “Better try harder…” Ask their age: If the user’s age is 65 or over, say “You are elegible for retirement benefits”, otherwise, say “Sorry, no benefits yet!” Ask what day it is: If the day is a Sunday, tell them they don’t have to feed the meter. If it is not Sunday, say: “Better get some quarters!” 46

47 If the user worked more than 40 hours, output “wow, a hard worker” ,
if not, output “Better try harder…” var hours; hours = document.form.txtHours.value; hours = parseInt(hours); if (hours > 40) { document.write("Wow, a hard worker!"); } else document.write("Better work harder!");

48 age = document.form.txtAge.value; age = parseInt(age);
Social Security Eligibility: var age; age = document.form.txtAge.value; age = parseInt(age); if ( age >= 65) { document.write("Eligible for SS benefits"); } else document.write("Wait a few years, sorry.");

49 day = document.form.txtDay.value; if (day == "Sunday") {
If the day is a Sunday, tell them they don’t have to feed the meter. If it is not Sunday, say: “Better get some quarters!” var day; day = document.form.txtDay.value; if (day == "Sunday") { document.write("No need to pay the meter!"); } else document.write("Better get some quarters!");

50 * if (day == “Sunday”) Why did we need quotes?
Supposing we had instead written: if (day == Sunday) In this case, JavaScript would think that Sunday was a variable. By placing the word ‘Sunday’ inside quotations, we are telling JavaScript that we are comparing the variable called ‘day’ with a String of text (value of ‘Sunday’)

51 Can your user spell better than a fifth grader?
A top-notch programmer will go out of their way to make sure that their program will work regardless of the crazy kinds of things that a user might try to do. This can occupy lots of time and code, but the idea is important. For example, what if in our parking-meter example, a user types ‘sunday’ (no capital)? Answer: the conditional would evaluate to false since “sunday” does NOT equal “Sunday”. (“sunday” == “Sunday”)  is FALSE

52 Anticipating different input:
Let’s re-write our conditional so that if the user enters “sunday” OR “Sunday” the conditional will hold true regardless. if (day == "Sunday" OR day == "sunday") … The word “OR” is not part of JavaScript. However, there IS a way of representing it: || The | (usually found above enter on your keyboard) is called the “pipe” character. Putting two pipes together (no space) is known as a “logical or”. *** When you have two or more comparisons separated by the “logical or” ( || ), what has to happen for the conditional as a whole to evaluate to true? Answer: If *ANY* of the comparisons is true, the entire conditional will evaluate to true. if (day == "Sunday" || day == "sunday") If either of the above comparisons is true, the entire conditional will be true if (day == "Sunday" || day == "sunday" || day== "Domingo" || day== "Vendredi" || day== "Sondag") Again, if ANY of the above comparisons is true, the entire conditional will evaluate as true.

53 If the day is a Sunday, tell them they don’t have to feed the meter.
If it is not Sunday, say: “Better get some quarters!” var day; day = document.form.txtDay.value; if (day == "Sunday" || day== "sunday" ) { document.write("No need to pay the meter!"); } else document.write("Better get some quarters!");

54 ** Logical “AND” ( && ): Suppose you wanted to write a statement where two (or more) conditions must be met for something to be done. For example, suppose you wanted to see if a user was registered to vote. You might want to ask: Is the user 18 years old AND Are they registered? In other words, both conditions have to be true. The syntax follows: if ( age >= && registered==“yes”) { alert(“You may vote”) } else alert(“You may not vote”); You can have as many conditions as you like inside the main conditional. When separated by logical AND ( && ), the rule is that ALL conditions must be true for the whole conditional to evaluate to true.

55 The conditional: if (………)
The conditional is the key component of ‘if’ statements. The condtion asks a question that must ultimately be evaluated as either ‘true’ or ‘false’ is the user less than 21 years old? if( age < 21)… is the due date later than today’s date? if (dueDate > todayDate)… is the user’s nationality American? (eg. customs) if (nationality == “American”)…

56 The conditional contd. Recall that conditionals ask a question, and that question must ultimately be answered as true or false. Typically this involves comparing two or more items and asking if one is greater (>), one is less (<), or if they are identical (==). There are numerous variations on this theme, but we’ll focus on these for now. To do these comparisons, we will use “relational operators”.

57 Relational operators The relational operators allow us to test the relationship between two items (frequently numbers). Equal == Not equal != Inequality >, >=, <, <= 57

58 ‘=‘ vs ‘==‘ Not difficult, but important.
We have frequently used ‘=‘ to assign. e.g. assign a value to a variable If we want to compare values, we can not use ‘=‘ because it is already used for assignments. Instead, we must use ‘==‘ if (name == “Bob”) …. if (age == 65) …. if (birthday == todayDate) ….

59 So, don’t forget… The moral is that you should carefully check that your if and if-else statements only use the equality operator ==. Typing = instead of == can produce unexpected behavior and this error can be very hard to find. 59

60 Retreiving info from select boxes
Recall that the document.form.elementName.value code that we’ve used for textboxes also works for other elements such as select boxes, and for textareas. Suppose you have a select box called ‘selNationality’. To retreive the value you could type: var country = document.Form1.selNationality.value; The value that gets retreived will be the one you encoded inside the <option> tag. Which particular option will depend, of course, on which option the user selected when they completed the form.

61 Determining if a checkbox is selected
We use the ‘.checked’ syntax – see next slide:

62 <script type="text/javascript"> function val() { if ( document
<script type="text/javascript"> function val() { if ( document.Form1.chkFirst.checked ) alert("first class"); if ( document.Form1.chkPet.checked) alert("Taking your pet!"); if ( document.Form1.chkSpouse.checked ) alert("Taking your spouse"); } </script> <form name="Form1"> <input type="checkbox" name="chkFirst" />First Class Only<br /> <input type="checkbox" name="chkPet" />Traveling with Pet<br /> <input type="checkbox" name="chkSpouse" />Traveling with Spouse<br /> <input type="submit" onClick="val()" /> </form>

63 ** Determining if a radio button is checked:
Radio buttons also use the ‘checked’ syntax, however, we have a problem: Multiple radio buttons have the same name. New York: <input type="radio" name="radCity" /> <br /> L.A <input type="radio" name="radCity" /> <br /> Washington <input type="radio" name="radCity" /> <br /> So how to we know WHICH button was checked? Answer: We refer to them by a number. Specifically, beginning with 0, each radio button is automatically assigned a number. That number is assigned in the order in which the buttons were typed into the HTML form. So for the radCity example above: The button for New York is number 0. The button for LA is number 1 The button for Washington is number 2. We can then use the same “.checked” value used for checkboxes: if ( document.form1.radCity[0].checked ) Alert(“Enjoy New York!”);

64 Retrieving the value of a radio button
It is important to realize that not all buttons have a value. Sometimes you simply want to know if a certain button was checked or not (e.g. a button for I Agree v.s. I Disagree). However, you do have the option of entering a value inside a radio button’s ‘input’ tag. If your button has a value, you can retrieve it using the same [ ] notation just discussed, along with the familiar ‘.value’ code: So: document.form1.radNationality[0].value will retrieve the value of the first radio button in the group called radNationality. See the next slide for an example.

65 Note how the numbers begin from 0
<script type="text/javascript"> function val() { if (document.form1.radCity[0].checked) alert("You are going to " + document.form1.radCity[0].value); } else if (document.form1.radCity[1].checked ) alert("You are going to " + document.form1.radCity[1].value); else if (document.form1.radCity[2].checked ) alert("You are going to " + document.form1.radCity[2].value); </script> <form name="form1"> New York: <input type="radio" name="radCity" value="New York" /> <br /> Los Angeles <input type="radio" name="radCity" value="Los Angeles" /><br /> Washington<input type="radio" name="radCity" value="Washington" /><br /> <input type="submit" onClick="val()" /> </form> Note how we identify each radio button using [] brackets Note how the numbers begin from 0 Note how the syntax: doc.form.radBtn.checked evaluates to true/false and can therefore be used inside a conditional.

66 Cascading if statements: if, and else-if
The examples we have just used involve only two possible scenarios: more than 40 hours or less? age over 18 or not? day is Sunday or not? In the real world, we frequently have multiple possible scenarios we want to evaluate for. For example, if the percent grade is , assign ‘A’ if grade is assign ‘B’ if grde is assign ‘C’ if assign ‘D’ if < 60 assign ‘F’ 66

67 var percent, letterGrade; percent = document. form. txtPercent
var percent, letterGrade; percent = document.form.txtPercent.value; percent = parseInt(percent); if (percent >= 90) { letterGrade = "A"; } else if (percent >=80) letterGrade = "B"; else if (percent >= 70) letterGrade = "C"; else if (percent >=60) letterGrade = “D”; else letterGrade = “F”; Remainder of the program continues…. *** How this works: As soon as one statement is evaluated as being TRUE, the code will enter the appropriate section (delineated by the braces). Once the section is complete (the closing brace is reached), the program will JUMP to the end of the entire group of if/else statements. This applies regardless of whether there is only 1 else statement or if there are thousands!

68 ** The ‘else’ statement:
var percent, letterGrade; percent = document.form.txtPercent.value; percent = parseInt(percent); if (percent >= 90) { letterGrade = "A"; } else if (percent >=80) letterGrade = "B"; else if (percent >= 70) letterGrade = "C"; else if (percent >=60) letterGrade = “D”; else letterGrade = “F”; Remainder of the program continues…. ** The ‘else’ statement: It is usually a good idea to have an ‘else’ at the end of a series of ‘else-if’ statements. If all of the ‘else-if’ statements are false, then the ‘else’ statement will be executed. However, the moment one of the else-if’s is executed, flow will jump to the end of the entier block of if-else statements (as discussed previously).

69 An example Review select_box_js.htm
IMPORTANT: Note how the value being read in from the select box is different from the value that gets displayed to the user. Recall: The value in between the <option> tags is what the user sees when they view your form. The value you encode in the value=“” attribute is what will be retrieved by the Javascript.

70 Exercise: Download the code for the BMI calculator we discussed earlier in the course. (See Week 4) We will use the following criteria to classify a patient’s weight: BMI < 18.5 = “Underweight” BMI 18.5 – = “Normal Weight” BMI 25 – = “Overweight” BMI >= 30 = “Obese” In addition to outputting the patient’s BMI, the program should also output their classification.

71 My version My version of the calculator is called bmi_calculator_class.htm and can be found under this week’s files.

72 Practice Here are a couple of additional exercises. These are VITAL for you to be able to do your final assignment properly and for your final exam. I will try to do these with you in class, but if we run out of time, you are expected to be able to work them out on your own. If this happens, I will provide the answers so you can check your work.

73 Exercise: Prompt the user for their income over the past year.  Then have a button that says “Calculate my taxes”.  Calculate their tax based on the following criteria: If the user has an income less than $30,000, their tax rate should be 0%.  If their income is between $30-49,999 their rate should be 25%.  If their income is between $50-99,999 use 35%.  $100,000 and more use 40%.  Output a result that says something like: For an income of $64,000, you must pay $22,400 in taxes.

74 Exercise: Prompt the user for the day of the week again by using a select box.  If they choose Saturday or Sunday (you MUST use the logical or “||” to do this) write an alert box that says:  “Have a great weekend!” If they choose Monday or Tuesday (you MUST use the logical or “||” to do this) alert: “Hope you had a good weekend” Wednesday alert: “Hump Day!” Thursday alert: “Almost there…” Friday, alert: “TGIF!”

75 Debugging Tips Note: As browsers are upgraded and versions change, the instructions may vary. Be sure to allow error messages by your browser In Internet Explorer: select Tools > Internet Options > Advanced Tab and check the box “Display a notification about every script error” In Firefox: select Tools > Error Console and click “Errors” (you may want to click “Clear” when starting) Safari: has a pretty good explanation. Error messages will be generated only for syntax errors and possibly runtime errors. Error messages will NEVER be displayed for logical errors. (e.g. having a calculation add when it was supposed to subtract, etc) 75

76 Debugging Tips Test it yourself!
Eg: If your program involves a calculation, pull out a calculator and check calculations by hand to make sure you didn’t code an error in your formula. Figure out exactly where the error occurs it might not be where you think – the debugger only tells you when the bug leads to an error. However the bug may have occurred at any point earlier in the program. 76


Download ppt "IT 130 – Internet and the Web - Yosef Mendelsohn"

Similar presentations


Ads by Google