Java Script
Java Script
Introduction to scripting
Learning Objectives
By the end of this lecture, you should be able to:
• In an HTML document, any script code must be placed inside a <script> tag
• You can place your scripting code anywhere inside the HTML document as long as it is inside
the <script> tag.
• However, most scripting code is grouped together at the very end of the <body> section.
Note the ; Semicolons are required at the end of nearly ALL lines of JS code.
Your code will often work without them, but it is good practice to include them.
In this course, they are required.
Case Sensitivity
• Many programming languages – including JavaScript— are
“case sensitive”.
• This means that upper case and lower case letters can not
be interchanged – they are considered to be completely
different letters!
• E.g.:
– alert("Hello World"); no problem
– Alert("Hello World"); will not display!
For this reason, whenever you look up code in a reference, be sure to pay
attention to case!
Case Sensitivity
• Here is an example from the MDN reference page showing a
function that returns the square root of a number.
• Note that the 'M' (in Math) is capitalized, while the 's' (in
sqrt) is not.
• In other words, when typing out this command, be sure to respect
these distinctions. Your code will end up with errors if you do not!
Only script code should be present in the <script>
tag
<html> (i.e. no HTML or CSS code should be present)
<head>
<title>First JS</title>
</head>
<body>
<script> Bad!
<h1>My First JavaScript</h1>
alert("Hello World");
</script>
</body>
</html>
Fun & Games with the alert() function
• We can place a variety of information inside the alert() function’s
parentheses. Here are some examples.
Note: The alert box is a JavaScript window, it is NOT a miniature web browser.
For this reason, you can not place HTML code inside an alert function.
Strings
• If you put information inside quotation marks, we call that text a ‘String’.
– You should know this term.
• Another example:
– alert("Date()"); --> Can you figure out what will appear?
Answer: The alert() function will output the string “Date()”
– alert(Date());
JS will attempt to execute the JS function called Date()
JavaScript Part
Organizing JavaScript Code into Functions
Invoking JavaScript Functions
Learning Objectives
By the end of this lecture, you should be able to:
4. The beginning and end of the body of the function must be delineated by braces:
{ and }
4. Note that while nearly all lines of JS code end with a semicolon, this does NOT
apply to function declarations (i.e. the first line of the function).
Reminder: Clarity
function myFirstFunction( )
{
alert("My first try at a function.");
alert("I hope it works.");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Functions Example</title>
</head>
<body>
<h2>Some JS code...</h2>
Note how the JS code is executed automatically when the page loads.
<script>
alert("Hello...");
</script>
</body>
</html>
Stand-Alone code
v.s.
Code inside a function
• If we place our JS code inside of a function, the code is NOT executed
automatically.
• This allows us to control if and when the code is executed. This is almost always
the desirable way of doing things.
• By placing JS code inside a function, It means that the code only gets executed
when we want it to.
• Recall that any stand-alone JS code is not only executed automatically, it is also
executed before any of the HTML content on the page is displayed.
• It also means that we can execute the function multiple times if need be.
• It also means that we have the option of deciding that in a given situation the
function should never be executed.
Code inside a function
The JavaScript code on this particular page will never be executed. The code is
contained inside a function – but at no point on the page did we ever invoke the
function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Functions Example</title>
</head>
<body>
<h2>Some JS code...</h2>
This JS code will never be executed!
<script>
function greetUser()
{
alert("Hello, user!");
}
</script>
</body>
</html>
How to execute ("invoke") a JavaScript function
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Functions Example</title>
</head>
<body>
<input type="button" value="Greet the user" onclick="greetUser();">
<script>
function greetUser()
{
alert("Hello, user!");
}
</script>
</body>
</html>
Executing a script from a form
• In this course, we will nearly always execute our scripts in response to the user submitting an HTML
form.
– Specifically, we will apply the onclick attribute to an HTML button.
• Let’s go through the process of creating a button that will execute a JavaScript function.
Aside: Note that the opening brace of the function is on the same line as the function declaration. This is fine – in fact, many users
prefer to place it there. The closing brace, however, should always be on its own line.
A common error:
• The function declaration should NEVER
have a semicolon after it.
function greetUser( );
{
alert("Hello...");
}
• Example:
var userName; Declaring the variable
userName = "Robert"; Assigning a value to the variable
30
Variables cont.
• You can create as many variables as you want in a script.
• A variable must only be declared once in a function. In other words, once you’ve declared a variable,
you do not declare it again.
• However, you can assign a different value to a variable over and over again.
– Every time you assign a value to a variable, the previous value that was stored in that variable replaced by the
new value.
• Here is an example of a simple script that declares two variables, one to store a quantity in U.S.
Dollars, and second to store a value in Mexican Pesos. We will then do a very simple mathematical
conversion and output the result in an alert box.
– Convention Alert! Note the naming convention we use when we name our variables. We use the same
camel-case naming that we used when naming functions.
Examine the following code. The full script is on the next slide.
var usDollars;
var mexicanPesos;
usDollars = 50;
mexicanPesos = usDollars * 12.87;
alert(mexicanPesos);
31
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Practice Makes Perfect</title>
</head>
<body>
<h1>It Takes Practice...</h1>
<input type="button" value="Convert Dollars to Pesos"
id="btnSubmit" onclick="dollarsToPesos()" >
<script>
function dollarsToPesos()
{
var usDollars;
var mexicanPesos;
usDollars = 50;
mexicanPesos = usDollars * 12.87;
alert(mexicanPesos);
}
</script>
</body>
</html> 32
Some Important Notes
Naming convention: Note that we use the same naming convention for our variable identifiers as
we’ve used for our function identifiers, i.e. camel-case.
Declaring variables: We typically declare one variable per line. However, if you have related
variables, we often will group them together on the same line with commas in between:
var firstName, middleName, lastName;
Declare at the top: We typically declare our variables at the top of a function, even if we are only
using them several lines below.
We can store any type of data into a variable such as numbers or strings (i.e. text).
Some examples:
temperatureCelcius = 33;
temperatureFarenheit = (9 / 5 * temperatureCelcius)+32;
userName = "John Doe";
userAddress = "222 Memory Lane";
34
STRINGS
• Strings are one of the very most important data types in programming.
• A combination of letters / words / symbols, etc is called a “String”.
temperatureCelcius = 33;
temperatureFahrenheit = (9/5* temperatureCelcius )+32;
alert(temperatureFahrenheit);
mathResult = Math.sqrt(25) + 5;
alert(mathResult);
36
File: temperature_conversion.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Practice Makes Perfect</title>
</head>
<body>
<h1>It Takes Practice...</h1>
<hr>
<input type="button" value="Convert 40 Celcius to Farhenheit"
id="btnSubmit" onclick="celciusToFahrenheit()">
<script>
function celciusToFahrenheit()
{
var fahrTemperature;
var celciusTemperature;
celciusTemp = 40;
fahrTemp = 9/5*celciusTemp +32;
alert(fahrTemp);
}
</script>
</body>
</html>
37
Examples of good and not-so-good identifiers
Let's look at some more examples using function names:
function convert()
- Not good! This identifier gives absolutely no idea of what the function is supposed to do.
function convertFarhenheitToCelcius()
- This is much better. A bit long perhaps, but there is nothing wrong with having a slightly long-ish
identifier if that identifier really explains what is going on.
- Don't overdo it though!
function convertFahrToCel()
- Also good. Given the context, most programmers would agree that this is pretty clear.
function fToC()
- Hopefully we can all agree that this is also a terrible identifier!
38
Examples of good and not-so-good identifiers
And a few more… Suppose we are writing a function that will ask the user for their
birthday:
function getDate()
- Not good. Are we looking up the current date? The date of the invasion of Normandy?!
function userBirthday()
- Definitely better, though the identifier we can't tell whether the function is reacting to a known
birthday (e.g. determining if the user is 21 or over), or if it is planning on doing something
based on their birthday such as reveal their horoscope, etc.
function getUserBirthday()
- Much better! It's not an overly long identifier, but gives a pretty good idea of what the
function is supposed to do.
39
Some rules for identifiers
When choosing your identifier, keep the following in mind:
It should typically begin with a lower-case letter, and then use camel case for subsequent words.
Don't forget: JavaScript is case sensitive so “firstName” and “FirstName” are different variables.
40
Reserved Words
• Here is a list of words that
can not be used as an
identifier.
• We call these 'reserved
keywords'.
• Most of these are words that
'mean something' in
JavaScript, e.g. function
or var.
• You do not need to
memorize this list. It's just
something you should keep
in the back of your mind
when you are choosing an
identifier.
41
JavaScript
Retrieving information from forms
Learning Objectives
By the end of this lecture, you should be able to:
– Describe where the information comes from when retrieving from a text
box or text area, as opposed to a form element that has a ‘value’
attribute.
– Comfortably retrieve values from textboxes, text areas, select boxes, and
store those values inside variables
– Do the above without looking at your notes
Retrieving values from a form using JavaScript
• As we have seen, creating this form using HTML code is pretty straight-forward.
• The next -- and key -- step is to learn how to retrieve the values that were entered
into this form (e.g. the value of the two text fields, and the value form the select
box) using JavaScript.
44
There are two ways to retrieve a value
In order to retrieve a value from a form, your form element must either:
1. Require the user to enter the value (e.g. via a text box or a text area)
In this case, the value we retrieve will be whatever the user has typed into the text box.
--- OR ---
2. Include a ‘value’ attribute, when you create the form element
– In this case, the value comes from form elements in which you (the developer) have included an attribute called ‘value’ ,
and then you – the programmer—chose a value for that attribute.
– For example, recall that when we created the <option> tags in our select boxes, we assigned values to them:
45
How to retrieve a value from a form element using JavaScript
The syntax is:
document.getElementById("ID-NAME").value;
For example, suppose our form has a text box with an ID of 'txtFirstName'. We could retrieve whatever the user entered in that text box AND store that value inside a
variable with the following line of code:
Important Notes:
• The word ‘document’ will not change during this course. It simply refers to the current web page.
• The value inside the parentheses must match with one of the ID names in your HTML document.
• The ‘value’ term says you wish to retrieve the value from that element.
• If the element you are getting the value of is a text field or text area, then the information you get back will be whatever was typed by the user.
• If your element has a built-in value attribute (e.g. select boxes), then that is the information that will be retrieved.
– Will retrieve the value selected by the user from a select box called ‘selMonthBorn’
– Suppose that one of the options in that select box was:
<option value="feb">Febuary</option>
– If the user selects that option, then the variable monthBorn will be assigned "feb".
Retreiving and storing information from a form element
• Once we retrieve a value from a form, where should we put it?
• This is one of the countless situations in programming where we use variables.
Can you predict what the lines of code are supposed do? Try to figure it out before
moving to the next slide.
firstName = document.getElementById('txtFirstName').value;
lastName = document. getElementById('txtLastName').value;
favoriteColor = document.getElementById('selFavoriteColor').value;
aboutUser = document.getElementById('textarAboutUser').value;
47
Retreiving and storing information from a form element
5. firstName = document.getElementById('txtFirstName').value;
6. lastName = document. getElementById('txtLastName').value;
7. favoriteColor = document.getElementById('selFavoriteColor').value;
8. aboutUser = document.getElementById('textarAboutUser').value;
– Learn a much better technique than alert() to output information to a web page
– Learn how to use a blank section as a placeholder for information you wish to output
Bye-bye alert()
It is time to say goodbye to an old friend. Though the alert() function has served us well, it should not typically
be used in the “real world”. At the very least, alert() should be reserved for only a few particular situations.
Therefore, we are going to pretty much retire alert boxes, we are now going to learn how to use a different JavaScript
command to output content directly into an existing web page.
Outputting using innerHTML
The following JavaScript code will output the words: Look at me! (in <h1> markup) into a section on the page that
has a ID named 'output':
IMPORTANT: It is very important to note that the innerHTML command replaces everything that was in that
section before. So in this case, the above command would replace everything that was previously inside 'output'
with the words Hello World!.
Imagine if that output section contained a whole bunch of important information that was there earlier. If you
then issued the innerHTML command, all of that existing content would be replaced with the words "Hello World!".
This is clearly not a desirable result.
Fortunately, there are various easy fixes. We will discuss one option next.
Creating an empty section
We will place an empty section in our document. The one and only job of this section is to hold the output of the
innerHTML command:
<div id="results">
</div>
The following JavaScript code will output the words: Look at me! in <h1> markup into our results div section:
1. The first line of code simply creates a variable that holds a string containing the content we want to insert into
our web document.
2. The second line inserts the string into the 'results' section.
<!DOCTYPE html> innerHTML_greeting.html
<html lang="en">
<head>
<meta charset="utf-8">
<title>Greeting with innerHTML</title>
</head>
<body>
<h1>innerHTML Example</h1>
<p>What is your name?
<input type="text" id="txtName">
<div id="greetingOutput">
</div> <!-- end of greetingOutput div -->
<script>
function greetUser()
{
var userName = document.getElementById("txtName").value;
document.getElementById("greetingOutput").innerHTML = greeting;
}
</script>
</body>
</html>
JavaScript
Concatenation of Strings
JavaScript Comments
Learning Objectives
By the end of this lecture, you should be able to:
Concatenation:
– Describe the two different operations carried out by the ‘+’ operator.
– Describe the circumstances under which the operator does addition,
and when it does concatenation.
– Join variables, literal text, and even numbers into a single string using
concatenation.
Comments:
– Be comfortable inserting comments in your code.
– Demonstrate how comments can be used to temporarily remove code
for debugging and testing purposes.
The lowly ‘+’ operator
We are all familiar with this operator… we use it for addition all the time.
• alert(5+2); outputs 7
• alert(5+5); outputs 10
However, this '+' operator is unusual in that it has two different uses. In addition to ‘adding’, the +
operator, if used with strings, can “concatenate” (join) those strings together.
– alert("H" + "e" + "l" + "l" + "o" + "."); ouputs: Hello.
– alert("Hello, " + "How are you?"); outputs: Hello, How are you?
57
Form values are retrieved as strings
The following is a very very important point
Any time you retrieve a value from a form, that value comes back as a string.
Even if the value looks exactly like a number, that "number" is in fact, a string!
Concept check: Can you predict what will be output by the alert box here?
var age;
age = document.getElementById('txtAge').value;
//Let's suppose that the user entered 25 for their age
alert(age+age);
• Because ‘age’ is holding a string (as opposed to a number), the ‘+’ operator will do concatenation as opposed to addition.
• This type of thing comes up a lot! And if we don't learn how to "fix" it, all kinds of errors and bugs in your code will result.
• Be absolutely certain that you understand this situation. It will be vital in upcoming assignments, and I can guarantee exam questions
relating to it!
58
Concatenation Example
Concatenation becomes extremely useful when we want to output the value of different strings and variables together. Consider this situation:
By concatenating the five strings together, this line of code will output all three variables in only one alert box.
Note the need to put spaces between each string. If we did not, we would end up with one long string.
59
Concatenation example
Study this example to ensure that you understand it.
As always, be sure to type out the example yourself and to experiment with it.
Incidentally, note how I typed a space before and after certain strings in our alert statements. If I neglected those
spaces, I hope you can see that the words would all be scrunched up against each other.
Next, experiment by placing the entire string in just one alert() window instead of two.
60
<!DOCTYPE html>
<html lang="en">
<head>
File: concat_ex1.html
<meta charset="utf-8">
<title>Practice Makes Perfect</title>
<script>
function testConcatenation()
{
var firstName, lastName, age;
firstName = document.getElementById('txtFirstName').value;
lastName = document.getElementById('txtLastName').value;
age = document.getElementById('txtAge').value;
<p><button onclick="testConcatenation()">Submit</button>
</form>
</body>
</html>
61
When Form Elements Go Rogue
File: age_next_year_no_parse.html
Be sure to study this example so that you can appreciate the problem.
(Explanation on the next slide)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Form Elements are Strings</title>
<script>
function calcNextYear()
{
var ageThisYear, ageNextYear;
ageThisYear = document.getElementById('txtAge').value;
ageNextYear = ageThisYear + 1;
alert("Next year, you will be: " + ageNextYear + " years old!");
}
</script>
</head>
<body>
<h1>How old???!!</h1>
<p>How old are you now? <input type="text" id="txtAge">
<p><button onclick="calcNextYear()" >How old will I be next year?</button>
</body>
</html>
62
New Topic: “Comments”
Recall that comments are very important in programming. As your code becomes increasingly
complex, you will find that including comments in yrou code makes life far, far more pleasant for
other programmers working with you on your code.
We have already discussed how to comment in HTML. Recall that placing text inside <!-- and -->
will case that text to be ignored by the web browser. That is, the text will be ignored by the interpreter
that is displaying content on the web browser.
Similarly, the JavaScript also has a syntax for including comments. In fact, it has two methods:
1. Placing two forward slashes // anywhere on a line of JS code tells the interpreter that anything
that follows is a comment and should be ignored.
If you have multiple lines you wish to “comment out”, then you must put the // characters before each
and every one of those lines.
2. If you wish to write several lines of comments (a common occurrence), it might be tedious to type
double slashes at the beginning of each line. In this situation, we can use "multi-line comments".
To do so, type /* Everything that follows until you type a closing */ will be treated as a
comment.
63
JavaScript
Data Types
Parsing Data
Learning Objectives
By the end of this lecture, you should be able to:
An argument is the information you provide to a function when you invoke it. Some functions require 0 arguments, others
may require 1 argument, and others can require multiple arguments.
This is a very simple term, but it is important that you are comfortable using it.
For example:
• alert('Hi'); --> the string 'hi' is the argument
• Math.sqrt(23.7); --> 23.7 is the argument
• Math.pow(3,4); --> this function has two arguments: 3 and 4
• Date(); --> this function has 0 arguments
66
Data Types
• In many programming languages, every piece of data that we work with has a “data type”.
• There are many different data types out there, but in this course, we will focus on three.
• Examples:
– x = "25" x is holding a String
– x = 25 x is holding an Integer
– x = 25.0 x is holding a Float
67
Examples
In each of the four assignment statements below, identify the value and data type that will be stored inside the variable number:
var x1 = "25";
var x2 = 10;
var x3 = 5.3;
var number;
number = x1 + x2;
Value: "2510" Data type: string
number = x1 + x3;
Value: "255.3" Data type: string
number = x2 + x3;
Value: 15.3 Data type: float
number = x2 + 4;
Value: 14 Data type: int
• In the first two cases, we have a string on one side of the ‘+’ operator. Recall that the moment a string is present on either side,
we will get concatenation.
• The third and fourth examples involve two numbers. In these case, then, the ‘+’ operator will do addition.
68
The parseInt() function
• JavaScript includes a very useful function that specializes in converting strings into integers. This function is called
parseInt().
• parseInt() accepts a piece of information (typically a string) inside its parentheses. (This piece of information is the
"argument" that we discussed earlier).
• The parseInt function then attempts to convert that information into an integer. If the information inside the parentheses
“looks” like an number, then great!
• If the information inside the parentheses does not look like a string, however, your script will generate an error and your page
will not display properly.
69
parseInt Examples
Can you predict what will be stored inside the variable ‘temp’ in each of the following examples?
1. var temp;
2. temp = parseInt("352");
3. temp = parseInt(49.99);
4. temp = parseInt("ten");
• Line 2?
• temp will store the integer 352
• The parseInt function has no difficulty converting this particular string to an int
• Line 3?
• temp will be assigned the integer 49
• The parseInt function has no difficulty converting this float to an int
• Important: Note that parseInt() does not round numbers up or down. Rather, the function simply chops off the decimal. We have a fancy word for this too (sorry):
“truncation”.
• Line 4?
• Error: As humans, we can easily figure out what is supposed to happen. Sadly, computers are unable to make that leap.
• IMPORTANT: A key point to know is that the value being converted by the parseInt function must "resemble" a number in order for parseInt() to be able to figure
out the conversion.
parseFloat()
What if the number you are planning to retrieve may contain decimals?
– E.g. The time to complete a 100 meter dash, the cost of a gallon of gas, etc
Recall that parseInt() stops parsing the instant it encounters any non numeric character – such as a decimal.
Therefore, if you want to keep your decimals, you would not want to use parseInt().
txtRaceTime
71
<!DOCTYPE html> File: parse_example.html
<html lang="en">
<head>
<meta charset="utf-8">
<title>Parse Example</title>
</head>
<body>
<h1>Parse Example</h1>
<p>How old are you now? <input type="text" id="txtAge">
<script>
function calcNextYear() {
var ageThisYear, ageNextYear;
ageThisYear = document.getElementById("txtAge").value;
ageThisYear = parseInt(ageThisYear);
ageNextYear = ageThisYear + 1;
alert("Next year, you will be: " + ageNextYear + " years old!");
}
</script>
Reminder: We are only using alert() functions in these examples to
</body>
minimize unrelated code. In the real world, we would use innerHTML.
</html> 72
<!DOCTYPE html>
<html lang="en"> File: fahrenheit_celcius_converter.html
<head>
<meta charset="utf-8">
<title>Temperature Converter</title>
</head>
IMPORTANT: One of the best ways to finesse your programming skills and learn new ones is by studying existing code.
<body> We will experiment with this approach here by introducing a couple of new points without several slides of formal
<h1>Temperature Converter</h1> “PowerPoint” discussion. However, I will provide some explanation.
<form id="conversionForm">
<p>Enter a temperature in fahrenheit: There are some important concepts discussed in this example – be sure to study it closely, and review periodically!
<input type="text" id="txtFahrenheit">
<button type="button" onclick="convertToCelcius()">Convert</button>
<!– We *need* the type attribute above! Otherwise our innerHTML won't work. -->
</form>
For reasons beyond the scope of this discussion, the innerHTML
<div id="results">
command won’t work unless we include the type="button"
</div><!-- end of results div -->
attribute. So, if ANY button is invoking a function that includes
innerHTML, be sure to include this attribute.
<script>
function convertToCelcius() {
To be on the safe side, feel free to include this attribute in all of your
var fahrenheit, celcius;
buttons if you like. (I’ve also included this on the assignment checklist).
var resultsString;
fahrenheit = document.getElementById('txtFahrenheit').value; Remember to close <div> sections with a comment indicating the name
fahrenheit = parseFloat(fahrenheit); of the section that was closed.
//people may well enter a decimal here, so use parseFloat
if (something is true)
{
Do this stuff here
}
else
{
Do this other stuff
}
Learning Objectives
By the end of this lecture, you should be able to:
If the conditional inside the parentheses is true, the code inside the braces
labeled ‘Block A’ will be executed. If the conditional is false, then the flow skips
the block. In that case, the code inside the braces after the else statement will
be executed.
However, if the ‘if’ condition is true, then once that “true” block has been
executed, the else block will be skipped.
76
Blocks can be as long/short as you like
if (conditional)
{
Block A statements
Block A statements
Block A statements
Block A statements
Block A statements
Block A statements
Block A statements
Block A statements
}
else
{
Block B statements
}
The code inside these blocks can be as short (e.g. one line) or as long
(e.g. 500 lines) as you wish.
77
Example – Movie Ticket
Example: We retrieve the value from a form in which we ask the user their age.
Our business requirements specify that a regular ticket costs $10, while a ticket for people 65
or over costs $5.
var age;
age = document.getElementById('txtAge').value;
age = parseInt(age);
In this example, regardless of whether or not the if block gets executed, the program will
simply continue on and complete the rest of the function. In this case, the program will
always alert “Goodbye”.
function determineBonus()
{
var hours;
hours = document.getElementById('txtHours').value;
hours = parseFloat(hours);
alert("Goodbye!");
}
Another example
Let’s write a script in which we ask the user for their age. If their age is 18 or over,
print: “You can rent a car!”
Take a moment to try and write the relevant code your own before looking at my
version. Start with a version that does not have an else block. Simply output “You can
rent a car” if the user is 18 or over. Assume the text field is called “txtAge”. You can
use alert() to keep things simple for the exercise.
var age;
age = document.getElementById('txtAge').value;
age = parseInt(age);
1. Ask the user how many hours they worked in the last week. If they worked more
than 50 hours, output “Wow, you’re a hard worker”. If they did not work over 50
hours, don’t say anything. Assume the text field is called “txtHours”.
– NOTE: Do NOT confuse ‘more than 50 hours’ with ‘50 or more hours’… One uses the
‘>’ operator, the other uses the ‘>=‘ operator.
var hours;
hours = document.getElementById('txtHours').value;
hours = parseFloat(hours);
81
Exercise
Ask their age: If the user’s age is 65 or over, say “You are eligible for retirement benefits”,
otherwise, say “Sorry, no benefits yet!” Assume the text field is called “txtAge”.
Again, feel free to use alert() since we are just practicing.
82
The conditional:
if (………)
Assignment Operator: Note that the ‘=‘ is an operation! It is called the “assignment’ operator” as we
use it to assign a value to a variable. However, this operator has very low precedence. It is almost always
the last operation on the line to be executed.
Parentheses: You can use parentheses to force the evaluation order: the innermost parentheses are
evaluated first. If you have any doubt about how things will be executed when writing a detailed
expression, it often helps to use parentheses.
86
<body> File: fahrenheit_celcius_converter.html
<h1>Temperature Converter</h1>
<form id="conversionForm">
<p><label for="txtFahrenheit">Enter a temperature in fahrenheit:</label>
<input type="text" id="txtFahrenheit">
<button type="button" onclick="convertToCelcius()">Convert</button>
<!– We *need* the type attribute above! Otherwise our innerHTML won't work. -->
</form>
<div id="results">
</div><!-- end of results div -->
<script>
function convertToCelcius() {
var fahrenheit, celcius;
var resultsString;
fahrenheit = document.getElementById('txtFahrenheit').value;
fahrenheit = parseFloat(fahrenheit);
//people may well enter a decimal here, so use parseFloat
document.getElementById("results").innerHTML = resultsString;
}
</script>
</body>
Another Lab Exercise:
Let’s write a page that calculates the “Body Mass Index” used in fitness circles as a
quick (though now mostly debunked) indicator of a person’s health.
The formula requires the user to enter their height and weight and then calculates
their BMI.
• The formula is: BMI = weight in pounds* 703 divided by height in inches
squared.
Try to create this page on your own before looking at my solution
The form:
For a weight of 180 pounds, and a height of 70 inches, your BMI is 25.8.
In addition to the infinite variety of user-defined functions that we could write ourselves, JavaScript also comes
with many, many 'built-in' or ‘predefined’ functions. The parseInt() and parseFloat() functions are
examples of such built-in functions.
Predefined functions are written by the creators of a programming language in order to solve many common or
anticipated coding situations that may arise. For example, the people who created JavaScript recognized that
programmers would quite likely need to access the date or time in their code, or that they would need to do
various mathematical operations. For this reason, the creators wrote a series of predefined functions to accomplish
these tasks.
We have seen and used several predefined functions already. Examples include:
• alert()
• getElementById()
• Date()
• Math.sqrt()
• parseInt()
• parseFloat()
• toFixed()
92
Example: Predefined functions in the Math class
93
Example: Predefined functions in the Math class
Clicking on the Math.sqrt(x) function brings us to this page:
94
File: die_roll.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dice Roller</title>
</head>
<body>
<h1>Dice Roll Game</h1>
<button type="button" onclick="dieRoll()">Roll the Die!</button>
<div id="results"></div><!-- end of results div -->
<script>
function dieRoll()
{
var die1, die2;
var resultsString;
die1 = parseInt(die1);
die2 = parseInt(die2);
document.getElementById("results").innerHTML = resultsString;
}
</script>
</body>
</html> NOTE: Every time you click the button, you are re-invoking the
dieRoll() function. So each time you click, you will see the
results of a new roll of the die. You do not need to refresh the page.
95
The Date object
We haven't discussed "objects" as that is beyond the scope of this course. However, try to follow
along with this example and the ones on the upcoming slide(s):
The variable 'today' is an object that holds all kinds of information about the current date including
the current hour, minute, second, month, day of the month, year, etc.
We can invoke various Date() functions using our today variable like so:
currentYear = today.getFullYear();
//currentYear holds the current year, e.g. 2021
currentHour = today.getHours();
//currentHour holds the hour as a number between 0 and 23
We have just discussed a couple of the functions that you can invoke on a Date() object. There are several
other useful functions such as getMinutes(), getSeconds(), etc. etc.
Pop-Quiz: How do you find out about other Date() functions that are available to you?
Answer: You look it up in the documentation! Practice by looking up the documentation and trying out some of
the other Date() functions.
Checking for “NaN” (Not a Number)
Recall that if JavaScript expects a number and does not get one, it will return the error: NaN
For example:
alert( parseInt("hello") );
There is a useful predefined JavaScript function that allows you to test for this particular error: isNaN()
if ( isNaN(age) )
alert("Please enter a valid age.");
else
alert("You are " + age + " years old!");
File: nan_test.html
The toFixed() function
This useful function allows you to specify the number of decimal places displayed by a numeric
value in a variable:
number = number.toFixed(2);
alert(number);
JavaScript:
Comparisons and Conditionals
Comparing for equality
Logical And/Or
Learning Objectives
By the end of this lecture, you should be able to:
Often this involves numbers (e.g. age>=65), but we also may want to compare, say,
two Strings.
For example, we may want to check if a user’s password matches the password on file.
102
Example 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!”
if (day == "Sunday") {
alert("No need to pay the meter!");
}
else {
alert("Better get some quarters!");
}
Notes:
– Remember that it’s perfectly okay to declare a variable and assign it a value on the
same line.
– It’s okay to have the opening brace of a block on the line that precedes the block.
– The closing brace should always be on its own line.
Multiple Conditionals Separated By Logical
ORs
Example:
if (day=="Sunday" || day=="sunday" || day=="Domingo" ||
day=="Vendredi" || day=="Sondag")
Answer:
It is perfectly acceptable – in fact, fairly common – to have multiple conditionals inside a
logical expression.
In the above example, because all of the conditionals are separated by logical ORs, as long as
ONE of the above conditionals is true, the entire logical expression will evaluate as true.
Parking meter example -- slightly improved version:
If the user says that today is Sunday – with upper-case or lower case ‘s’, tell them
they don’t have to feed the meter.
if (day=="Sunday" || day=="sunday" )
{
alert("No need to pay the meter!");
}
else
{
alert("Better get some quarters!");
}
Multiple Conditionals Separated By Logical ANDs
(&&)
Also very common are situations in which two or more conditionals must ALL be
True:
• As with OR statements, you can have as many conditionals as you need inside the
logical expression.
Summary: When separated by logical AND (i.e. && ), the rule is that ALL conditionals
must be true in order for the logical expression to evaluate to true.
Multiple Conditionals are Perfectly
Acceptable
You can have as many conditionals as you like inside the logical expression.
Also, recall that when multiple conditionals are separated by the logical and operator,
&&, all of the conditionals must be True for the whole logical expression to evaluate
to True.
Using braces for ‘if’ statements
If your ‘if’ statement has only one line of code, the braces are optional.
– if (logical expression)
{ more than one
statement 1 statement – braces are
statement 2
}
required
In general, I recommend that you ALWAYS use braces – even in those cases
where your block is only one statement long. Only once you get very
comfortable, should you use this shortcut.
108
<body> vote_check.html
<h2>Vote Checker</h2> (partial)
<form id="voterInfo" class="form-style-classic">
<p>How old are you? <input type="text" id="txtAge" size="10"></p>
<p>***
<button type="button" onclick="checkVoterEligibility()" style="background-color:#ffff99;">
Can I Vote?</button>
***</p>
</form>
<script>
function checkVoterEligibility()
{
var age, isFelon, isRegistered;
age = document.getElementById('txtAge').value;
age = parseInt(age);
isRegistered = document.getElementById('txtRegistered').value;
isFelon = document.getElementById('txtFelon').value;
• The if / else examples we have been using so far have involved only
two possible scenarios, that is, a situation that has only one of two
possible results. For example:
– Pay the meter or not?
– Pay overtime or not?
– Qualified to vote or not?
if (percent>=90)
Sometimes we need or want an
{
else block, and sometimes we letterGrade = "A";
do not. It depends on the }
situation. else if (percent>=80 && percent<90)
{
letterGrade = "B";
}
The else block gets executed else if (percent>=70 && percent<80)
ONLY if all of the prior logical {
expressions are false. letterGrade = "C";
}
else if (percent>=60 && percent<70)
However, the moment any {
letterGrade = "D";
block gets executed, flow will }
jump to the end of the entire else if (percent>=0 && percent<60)
block of if / else if / else {
letterGrade = "F";
statements (as discussed }
previously). else
Again, this includes the ‘else’ block. {
alert("Percent grade must be
greater than 0.");
}
JavaScript:
– Understand and describe why it’s a good idea to limit free-text entry by
users
– Apply various techniques for limiting free-text entry
Limiting / Avoiding Free-text Entry by Users
When visitors to your web page are allowed to type in data on their own, there is tremendous opportunity for bugs – and even hacking. For example,
hackers have successfully entered JavaScript code into text fields and used that code to gain entry to “secure” systems and do tremendous damage.
On a more benign level, imagine you want the user to tell you the day of the week (recall our parking meter example). Will they enter Sunday, sunday,
SUNDAY? What about typos? Ssunday, Sunda, etc, etc.
This is why web designers will, whenever possible take the option for entering text out of the user’s hands. There are many techniques for doing so
including the use of
Select boxes (e.g. for day of the week)
Check boxes (I agree/Disagree)
Radio Buttons (rate from 1 to 10)
Calendar widgets (for dates)
Etc.
Generally speaking, you should only allow the user to enter text where it is absolutely required. Some examples:
– Name
– Email Address
– Address
– Phone number
Eliminating free-text entry
Recall our parking meter example in which we
<!DOCTYPE html>
asked the user what day or the week it was. We then <html lang="en">
had them type the day of the week into a text box. <head>
<meta charset="utf-8">
<title>Parking Meter</title>
</head>
Now that we know that this is something to avoid, <body>
let’s redo the example but instead of using a text <header>
<h1>What day is it?</h1>
field, we will use a select box. </header>
<main>
Choose one:
Here is the code for the web page itself. Before <select id="selDayOfWeek">
<option value="su">Sunday</option>
looking at my solution, try to convert this into a <option value="mo">Monday</option>
working program in which if the day is Sunday, you <option value="tu">Tuesday</option>
<option value="we">Wednesday</option>
tell the user to pay the meter. If it is not Sunday, you <option value="th">Thursday</option>
tell them that they do not have to. <option value="fr">Friday</option>
<option value="sa">Saturday</option>
</select>
<button type="button" onclick="determinePayment()">
My version of the solution (which may well differ Do I need to pay?</button>
from yours) is on the next slide. But DO work it out <p>
<div id="output_area">
on your own before looking at my answer. </div> <!-- end of output_area div -->
</main>
<script>
WRITE YOUR FUNCTION HERE
</script>
</body>
</html>
118
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Parking Meter</title>
File: parking_meter_select.html
</head>
<body>
<header>
<h1>What day is it?</h1>
</header>
<main>
Choose one:
<select id="selDayOfWeek">
<option value="su">Sunday</option>
<option value="mo">Monday</option>
<option value="tu">Tuesday</option>
<option value="we">Wednesday</option>
<option value="th">Thursday</option>
<option value="fr">Friday</option>
<option value="sa">Saturday</option>
</select>
<button type="button" onclick="determinePayment()">
Do I need to pay?</button>
<p>
<div id="output_area">
</div> <!-- end of output_area div -->
</main>
<script>
function determinePayment() {
var outputString;
var dayOfWeek = document.getElementById("selDayOfWeek").value;
if ( dayOfWeek != "su" )
outputString = "You must pay the meter!"; Where are the braces?
else Recall that if the block of an if or else or else if statement
outputString = "You do not have to pay the meter!"; is only one statement long, then the braces are optional.
document.getElementById("output_area").innerHTML = outputString;
}
</script>
</body> 119
</html>
Eliminating free-text entry
Suppose you wanted to ask the user their favorite Chicago sports team. Will they enter: Cubs, cubs, Chicago cubs,
Sox, White Sox, White-Sox, CWS, Hawks, Blackhawks, BLACKHAWKS!, etc, etc, etc. In other words, we have
absolutely no idea what the user may type!
Depending on the team they choose, we output “You are a fan of the Chicago Blackhawks“ (or whichever team they
selected).
Again, our solution to this problem is to take away the user’s ability to enter any free text at all. Instead, we use form
elements such as radio buttons, or, in this case, a select box.
120
<h1>What is your favorite Chicago sports team?</h1>
File: favorite_sports_team.html
<option value="choose">Choose One</option>
<option value="cubs">Cubs</option>
<option value="sox">Sox</option>
<option value="bears">Bears</option>
<option value="hawks">Blackhawks</option>
<option value="other">None of the Above</option>
</select>
<div id="output_area">
</div> <!-- end of output_area div -->
<script>
function checkTeam()
{
var outputString = "You are a fan of the Chicago ";
//We will concatenate onto this string the team that they choose.
if ( team=="cubs" )
{
outputString = outputString + "Cubs."; //Concatenate “Cubs.” onto the variable ‘outputString’
}
else if (team=="sox")
{
outputString = outputString + "White Sox.";
}
else if (team=="bears")
{
outputString = outputString + "Bears.";
}
else if (team=="hawks")
{
outputString = outputString + "Blackhawks.";
}
else if (team=="other")
{
outputString = "Not a sports fan?";
}
if (team!="choose") //We output ONLY if they chose one of the options from the select box
{
document.getElementById("output_area").innerHTML = outputString;
}
} 121
</script>
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) output: “Have a
great weekend!”
– If they choose Monday output: “Hope you had a good weekend”
– If they choose Tuesday OR Wednesday OR Thursday output: “Mid-week Blahs”. (Note: Use
your OR operators for these three).
– Friday, alert: “TGIF!”
– For this program, place the onclick attribute inside the <select> tag.
122
JavaScript
Working with ‘checked’ items
Checkboxes and Radio buttons
Learning Objectives
By the end of this lecture, you should be able to:
Example: Suppose you have a select box called selNationality. To retreive the
value you could type:
The value that gets retreived will be the one you encoded inside the <option> tag.
Similarly, for text boxes and textareas, the value retrieved is the information that was
typed in by the user.
Determining if a checkbox or radio buton is checked
But what if there is no text? For example, what if you are simply working
with a checkbox or a radio button and simply wish to know if the button was
checked or not?
Answer:
We use
document.getElementById('element_name').checked
<input type="checkbox" id="chkFirst">First Class Only
<input type="checkbox" id="chkPet">Traveling with Pet
<input type="checkbox" id="chkSpouse">Traveling with Spouse
<script>
function doStuff()
{
if (document.getElementById('chkFirst').checked)
alert("Going in style!");
if (document. getElementById('chkPet').checked)
alert("Taking your pet!");
if (document. getElementById('chkSpouse').checked)
alert("Taking your spouse");
}
</script>
Retrieving the value of a radio button
With things like text fields and select boxes, we must ultimately retrieve a 'value'. After all,
that is the whole point of those particular types of form elements.
However, with checkboxes and radio buttons, this is not necessarily the case. That is, with
things like checkboxes / radio buttons, we often only need to know if the box/button was
checked.
However, while your radio buttons and checkboxes do not necessarily have to have a value,
it is often very useful to do so. If your radio button (or checkbox) does contain a value
attribute, you can retrieve it using the familiar ‘.value’ syntax. Again, though, whether or
not you choose to include a value is a matter of context in terms of how you set up your
page.
For example, in the following radio buttons, we have include a 'value' attribute:
What is your favorite color?
RED <input type="radio" name="favColor" id="radFavRed" value="red">
BLUE <input type="radio" name="favColor" id="radFavBlue" value="blue">
You could retrieve the value of the 'value' attribute of any of the buttons as follows:
var favoriteColor = document.getElementById("radFavRed").value;
//favoriteColor will hold the value "red"
Retrieving the value of a radio button
What is your favorite color?
if (document.getElementById("radFavRed").checked)
{
favoriteColor = document.getElementById("radFavRed").value;
}
else if (document.getElementById("radFavBlue").checked)
{
favoriteColor = document.getElementById("radFavRed").value;
}
<!-- Recall that we give all the radio buttons the same name so as to group them together.
This way, the user can only select one button from this group. -->
<div id="output">
</div>
</form>
<script>
function checkCity()
{
var outputMessage = "You are going to ";
var cityChoice;
if (document.getElementById('radNy').checked)
{
cityChoice = document.getElementById('radNy').value;
}
else if (document.getElementById('radLa').checked )
{
cityChoice = document.getElementById('radLa').value;
}
else if (document.getElementById('radWash').checked )
{
cityChoice = document.getElementById('radWash').value;
}
• Prompt the user for their income over the past year. Then have radio
buttons for the 4 options shown below. 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 $30K (i.e. $30,000), their tax rate should be 0%.
– If their income is between $30K and below $50K their rate should be 25%.
– If their income is between $50K and below $100K, use 35%.
– $100,000 and more use 40%.
– Round the result to 0 decimal places.
131