Title: JavaScript
1JavaScript
- Client-side dynamic documents
2JavaScript Capabilities
- Add content to a web page dynamically.
- Alter a web page in response to user actions.
- React to user events.
- Interact with frames.
- Manipulate HTTP cookies
3JavaScript is not Java
- JavaScript is a very simple scripting language.
- Syntax is similar to a subset of Java.
- Interpreted language.
- Uses objects, but doesn't really support the
creation of new object types
4Language Elements
- Variables
- Literals
- Operators
- Control Structures
- Objects
5More JavaScript Basics
- ltscript languageJavaScriptgt
- document.write(Hello, World!)
- lt/scriptgt
- We can put as many commands inside of the
ltscriptgt container as we like. - The write method will write whatever data we
want to the document, allowing it to appear on
the screen.
6JavaScript in HTML Documents
- We can put JavaScript is either the HEAD of BODY
of a document. - Even with a write command in the HEAD of the
document, the text will still appear in the BODY
of the document.
7Embedding HTML in JavaScript Output
- We can put as much (or as little) HTML as we like
in with our JavaScript. - The HTML that we put in with our JavaScript will
be used to mark up the document. - We must print the HTML elements we cannot
just put them around the JavaScript commands.
8Embedding (contd)
- Yes
- document.write (ltbgt)
- document.write (Hello, World!)
- document.write (lt/bgt)
- No
- ltbgt
- document.write (Hello, World!)
- lt/bgt
9More JavaScript Basics
- Although multiple write() commands may be used,
HTML will still ignore the different lines and
put the words together. - If we want to force a new line to start, we have
to use ltbrgt. - If we want a new paragraph, we have to use ltpgt.
10Example
- document.write(Hello,)
- document.write(How are you?)
- This above text will appear all on one line. If
we want the text to be on different lines, we
have to do the following - document.write(Hello,)
- document.write(ltbrgtHow are you?)
11What is a Variable?
- A variable is a named storage spot where we can
store information. It is a little like a box
where we can temporarily put information that we
want to use later on. - Variables are very useful when programming they
allow us to retrieve information from the user
and use it at a later point in time.
12Prompting For Storing User Input
- In order to prompt the user for information, we
can use the prompt() function. - We can store the result of the prompt() function
in a variable. - The information entered by the user will be
stored in the variable name for use at a later
point in time.
13Prompting and Storing (contd)
- The order in how we do this is important.
- First, we have to create the variable. We can do
this using the following command - var name
- Where var tells us that it is a variable and
name is the name of the variable. There is now
a spot in the computer that is going to hold
information, and that spot is called name
14Prompting and Storing (contd)
- Once we have declared the variable, we can prompt
the user for information and store it in the
variable - nameprompt(Enter your name.)
- This will take information from the user and will
store it in the variable name. We will be able
to access the variable at a later point in time
to use the information retrieved from the user.
15Using Variable to Retrieve Info
- If we want to use information stored in a
variable, all we have to do is use the variable
where we want the data. - document.write(name)
- Note that we do not use quotes around name when
using the variable. If we used quotes, the
computer would think that we wanted to print the
word name on the screen. By just using name, it
uses the value stored in that variable.
16An Example
- ltscript languageJavaScriptgt
- var name
- nameprompt(Please enter your name)
- document.write(Hello, )
- document.write(name)
- lt/scriptgt
17More Prompting
- When we use the prompt() function, we can also
enter default information into the field. This is
done by using a second parameter. - prompt(Question, default text)
- The default text will appear in the editable
field where the user is supposed to put their
data.
18Multiple Variables
- We can use multiple variables when using
JavaScript. This means that we are able to handle
multiple different inputs from the user. - Once we have access to the different variables,
we can use them how we wish. - It is important to point out that a variable can
be use as many times as needed.
19Multiple Variable Declaration
- We can declare multiple variables two different
ways - One per line
- var first_name
- var last_name
- Both on the same line
- var first_name, last_name
20Retrieving Multiple Pieces of Data
- var first_name, last_name
- first_nameprompt(First name?)
- last_nameprompt(Last name?)
- document.write(first_name)
- document.write( )
- document.write(last_name)
21Variable Naming
- We can assign many different names for variables,
helping us to keep track of what is actually
stored in the variable. - It is important to choose appropriate names, as
that will help us to keep track of the data. - There are a few naming rules that we have to
follow.
22Variable Naming Rules
- Names can be composed of
- letters
- numbers
- the underscore.
- Names cannot
- have spaces or special characters
- start with a number
- Names are also case sensitive!
23Examples
- var first_name
- var first name
- var FirstName
- var firstname
- var name1
- var 1name
- var firstname
24Storing Strings
- We have stored words in the variables such as our
first name and our last name. - These pieces of information were collections of
characters. We refer to these collections of
characters as strings. - A string is any collection of characters that we
find on the keyboard.
25Storing Numbers
- We can also store numbers in our variables.
- In order to store numbers, we have to tell the
computer (using JavaScript) that the data stored
in the variable is a number and not a string. - If we do not tell the computer that we have a
number, it will treat the digits like a string.
26Value Representation
- In order to help us understand the difference
between a string value and a numeric value, we
usually show our strings surrounded by quotes
(). - Quotes are often used to represent strings.
- number 45 ? a string of two digits
- number 45 ? the integer 45
27Reading Input
- When we prompt for information from the user, it
is always stored as a string. - Some math operations might work with the
variables, but not all. - When in doubt, the computer will treat any input
as a string. - We can convert string variables to numeric
variables.
28Number Types
- There are two different types of numbers floats
and ints. - A float is a number with a decimal point (a
floating point number). - An int is a number without a decimal point (an
integer). - If we want to convert a string to a number, we
have to decide which numeric type we want to
convert it to.
29Floats
- In order to convert strings to floats, we use a
function called parseFloat() - We parse the number from the string variable.
This removes the number from the string, storing
it as a numeric value. - The parse function will even remove extra
characters that may happen to follow the floating
point number in the prompt field. It will not
remove characters that appear before the first
character.
30parseFloat()
- var x, y, answer
- x prompt(Enter a number)
- x parseFloat(x)
- y prompt(Enter a second number)
- y parseFloat(y)
- answer x y
- document.write(x, , y, , answer)
31Explanation
- We can use the values stored in x and y to create
a new value to store in answer. - We can use all three variable again to write
information to the screen. - When using the write command, we have the option
of including multiple items to be written, as
long as they are separated by a comma. - We have to include the appropriate spacing for
the output to look correct.
32What about ints?
- We can get an integer from a string by using the
parseInt function. - This function will retrieve an int from the
entered text. - As with the parseFloat function, trailing letters
will be removed, while leading letters will cause
an error. - parseInt will also remove anything to the right
of the decimal point.
33parseInt vs. parseFloat
- If you enter 4.3f as the value into the prompt,
then 4.3f will be stored in the variable. - If we use parseFloat, we will end up with the
variable value of 4.3 - If we use parseInt, we will end up with the
variable value of 4
34What about other math operations?
- subtraction - works fine
- division / works fine
- multiplication works fine
- We can use these functions to do basic math on
our web pages.
35What about Strings?
- We can perform math operations on variables that
are numbers, but do these math operations work on
strings? - Do any of the math operations work with strings?
- If math operations dont work on strings, what
results do we get to tell us that we have an
error?
36String Operations
- will concatenate two strings together, so if
xbob and ybill, xybobbill - -, , and / will all fail. The result on
the screen for these equations will be NaN. - NaN stands for Not a Number, as the result
from these equations is not a valid number.
37Errors
- JavaScript will give us errors if we try to do
something that it doesnt like. - The errors may involve something printed to the
screen, or it may involve nothing printed to the
screen. - We will need to be able to figure out where the
errors are and fix them.
38Errors (contd)
- My personal suggestion
- write your JavaScript in fairly small, logical
sections - test each section to make sure that it works
- once one section works, move to the next section
- If an error is introduced, then you will know
which lines of code have caused the problem.
39Errors (contd)
- If you are unsure of how some piece of JavaScript
works - you can look it up online to see how it works
- you can write a small program and see how it
works - By writing code to see how things work, you can
answer your own questions quickly about
JavaScript. It is a good way to learn how to
program.
40Error Types
- There are three different types of errors
- syntax errors
- logic errors
- user errors
- We must be able to determine the difference
between these errors in order to be able to
correct them.
41Syntax Errors
- A syntax error is an error created by incorrectly
typing in JavaScript statements. - An example would be
- write.document(Hello, World!)
- The missing quote will cause this statement to
fail. - Such statements may simply not work in our
browsers.
42Logic Errors
- Logic errors occur when we make a mistake in the
logic of our statements. - For example
- number 50 100 / 2
- number (50 100) / 2
- If we really mean the second one and we type in
the first one, we will have a logic error. - We have to be careful that the logic of the
program is correct.
43User Errors
- User errors are caused when the user enters in
the wrong information. - If we expect the user to enter in a number and a
letter is entered instead, then this can cause
lots of problems. - There are ways that we can double-check to see
what the user has typed in, helping to avoid this
problem. We will learn of these methods later.
44Writing Readable Code
- Once again, writing readable code is important.
The easier it is to read, the easier it will be
to understand and to find errors. - We are able to write our programs in a couple of
different ways. We should choose the method that
makes the code as easy to read as possible.
45Variables Statements
- We must declare our variables before we use them
in our program. - It doesnt make a difference where we declare our
variables, as long as they are declared before
they are used. - In order to make our code more readable, we
should declare all of our variables at the top of
our program. It makes the code easier to read.
46Variables Statements
variable declarations
program
programming statements
47JavaScript Variables
- Un-typed!
- Can be declared with var keyword
- var foo
- Can be created automatically by assigning a
value - foo1 blah"Hi Dave"
48Variables (cont.)
- Using var to declare a variable results in a
local variable (inside a function). - If you don't use var the variable is a global
variable.
49Literals
- The typical bunch
- Numbers 17 123.45
- Strings "Hello Dave"
- Boolean true false
- Arrays 1,"Hi Dave",17.234
Arrays can hold anything!
50Operators
- Arithmetic, comparison, assignment, bitwise,
boolean (pretty much just like C). - - / -- ! gt lt
- ! ltlt gtgt
51Control Structures
- Again pretty much just like C
- if if-else ? switch
-
- for while do-while
- And a few not in C
- for (var in object)
- with (object)
52Objects
- An object is a definable thing, such as a car.
Objects are allowed to have other objects a car
can have a trunk, the trunk may have a spare
tire. - Since JavaScript is an object-oriented language,
we use dot syntax to specify the relationship
between objects. - car.trunk.sparetire
53Objects
- Objects have attributes and methods.
- Many pre-defined objects and object types.
- Using objects follows the syntax of C/Java
- objectname.attributename
- objectname.methodname()
54Instance
- An instance is a particular incarnation of an
object. - For example, I could represent students in the
class using class.student, where an instance of
the student object would be a particular person. - An instance of an object has all of the same
attributes as that object.
55Objects
- In real life, and object is a tangible thing
a car, a bike or a computer. - As we can see, we like to name objects so that we
can talk about them. - The object name doesnt define the object, but it
acts as more of a reference to the object itself.
56Objects (contd)
- When programming, we use objects as a reference
name for information that we want to store. - We use programming objects to store information
about real-life objects. - We store object data by storing information about
the individual attributes or properties of the
object in question.
57Object Information
- For example, if we have a green bowling ball that
weighs 3kgs, we know that - the bowling ball color is green
- the bowling ball shape is round
- the bowling ball weight is 3kgs
- In each of these cases, we are associating an
attribute with a piece of data describing that
attribute.
58Creating an Object
- In JavaScript, we can create an Object using a
function. In this case, we can create a bowling
ball object - var bball new Object()
- This code creates a new object called bball.
- The new Object() function is called a
constructor function because it is used to
construct a new object.
59Storing Object Information
- If we have an object called bball, we can store
information about that object - bball.color blue
- bball.shape round
- bball.weight 3
- bball.holes true
- We can store as much information as we want about
bowling balls.
60Object Information
- We associate the properties of the object with
the object using a . - This allows us to associate the parameter to a
particular object. - For example, we could easily store the color of
multiple different objects. Using the object name
will help us keep track of the information.
61Object Info (contd)
- bball.colorgreen
- car.colorred
- If we were to say
- document.write(color), we wouldnt know which
color to print out. - Instead, we can refer to the information based on
the object - document.write(bball.color)
- document.write(car.color)
62Object Attributes
- We can add as many attributes to an object as we
like. - It is advisable to keep the number of attributes
to the minimum needed. - We should also declare all of the attributes in
the same location, making it easier to keep track
of them.
63Primitive Types
- Considering that an object is an new type of
variable, we can now refer to ordinary variables
as primitive types. - A primitive type is a one of the regular
variables that we can store. - There are three primary primitive types
numbers, strings and Booleans.
64Compound Objects
- A compound object is an object where some of the
attributes are other objects. - For example, one attribute of a person object
might be their name. - name itself can also be an object, as it can be
comprised of a first, middle and last name. - In this case, the object name is an attribute of
the object person.
65Compound Objects (contd)
parent
child
first middle last
Name
Person
Age
66Using Compound Objects
- We can use compound objects in the same way that
we used variables. - The advantage of compound objects falls with the
ability to logically manage the object. - We are able to store all of our related
information in a logical object.
67More Objects
- The document object is a compound object.
- The document object is part of the larger window
object. Each of these objects has attributes that
we can access.
68The Window Object
- window.closed (Boolean)
- window.location (String)
- window.history.length (Number)
69The document Object
- The document object is special in the window, so
there is no need to specify the parent window
object. - This allows us to use document.bgColor instead
of window.document.bgColor. - There are many other document attributes that we
can access.
70document attributes
- document.bgColor (String)
- document.fgColor (String)
- document.URL (String)
- document.lastModified (String)
- document.linkColor (String)
- document.vlinkColor (String)
71Object Methods
- A method is a function an object can use to
perform various tasks. - We have already seen an object method the write
method associated with the document object. - The write method is used to tell the document
object to add some information to the page. - This is why we say document.write(foo)
72Object Methods (contd)
- Methods are a powerful method of modifying
objects. - Creating methods for objects that we have created
is out of the scope of this course, but we will
take advantage of those methods available to us
from the window, document and other objects.
73window.confirm()
- The confirm() method of the window object will
ask the user a question and get a result either
true or false, depending on which button they
push. - We can store the results of the question in a
variable. We can use the variable later in the
program to perform some action.
74Example
- var question
- question window.confirm(This is a question
where you have to answer OK or Cancel. OK is
true, Cancel is false. Do you understand?) - if (question)
- document.write(You understood.)
-
- else
- document.write(You didnt understand.)
75window.location
- window.location is responsible for telling the
window to load a new webpage. - If we say window.locationhttp//www.csuhayward.ed
u, we will be transported to the Hayward homepage.
76window.history
- We can also use the window history to go back to
previous webpages. - For example, if we want to bring the user back to
the page they just arrived from, we can use
window.history.go(-1) to bring them back one
page. We can go back as many pages as we like.
77Properties
- Object can have properties. These properties are
responsible for identifying and storing
information about the object. - For example, in the example of class.student,
each instance of student would have a property
called name. - We can access the property using the dot syntax
for class.student.name
78Values
- We can set the values of object properties for
instances of an object. - In our student example, we can set the name of
the student in the following way - class.student.name Frank
- Likewise, we can apply this to our document
object - window.document.bgColorred
79Accessing Values...
- If we include an image in our webpage and give it
a name, we can access it as a property. - ltimg srcimage.jpg nametestPic
altpicturegt - can be accessed by
- document.testPic.srcimage.jpg
80Accessing Values
- Likewise, if we set the background color of our
webpage to grey using - ltbody bgColorgreygt
- We can also access that same property using
- document.bgColorgrey
81Events
- In real life, objects can encounter events.
- An event is some action that has happened.
- If we can identify an event that may happen to a
webpage, we can watch for that event to happen. - One example would be to watch where the mouse is
placed on the screen.
82Event Handlers
- When we see an event happen, we have to handle
the event. - One such event is mouseover, when the mouse is
placed over an object in the webpage. - This event can trigger an action, such as
changing the picture that the mouse is over.
83Mouseover Event
- Our event handler is responsible to doing
something when the event has happened. - lta href
- onmouseoverdocument.bgColorgreengt
- This is some textlt/agt
- This will change the background color to green
when we put the mouse over the link.
84onmouseout event
- We can also make things happen when the mouse is
removed from the object (like when the mouse is
removed from on top of the link or picture). - This is known as the onmouseout event, and
works in the same way. - There are other mouse events that we will talk
about later
85Variables
- We have already seen some variables used in our
simple programs. - We can set the value of a variable to whatever we
want, and we can use the variable wherever we
would use the value. - Variables can be reused as many times as we want
in a program.
86Arrays
- An array is just an ordered collection of data.
- If we want to store 10 pieces of similar
information, an array is easier than coming up
with 10 unique variable names. - Arrays are indexed with a number.
- var pets new Array()
- pets0 Fluffy
- pets1 Sparky
87Arrays (contd)
- Arrays usually start at 0 and go from there.
- Some programmers like to start their arrays at 1
as they believe that this is more natural and
easier to understand. - As long as you are consistent, it doesnt really
make a difference (although I do prefer to start
arrays at 0)
88Methods
- Methods are actions that are associated with
objects. These actions are often triggered by
events or called in the middle of a program. - For example, the document object has a method
called write which takes care of putting
information to the browser. - We call the method using the dot notation
document.write(text)
89Functions
- A function is a group of statements that have
been collected together to perform a specific
task. - Functions are grouped in such a way that they can
be reused many times in a single program. - We can call a function in the same way that we
would call a method, just by using the function
name.
90Array Objects
- Arrays are supported as objects.
- Attribute length
- Methods include
- concat join pop push reverse sort
91Array example code
- var a 8,7,6,5
- for (i0ilta.lengthi)
- ai 2
- b a.reverse()
92Many other pre-defined object types
- String manipulation methods
- Math trig, log, random numbers
- Date date conversions
- RegExp regular expressions
- Number limits, conversion to string
93Predefined Objects
- JavaScript also includes some objects that are
automatically created for you (always available). - document
- navigator
- screen
- window
94The document object
- Many attributes of the current document are
available via the document object - Title Referrer
- URL Images
- Forms Links
- Colors
95document methods
- document.write() like a print statement the
output goes into the HTML document. - document.write("My title is" document.title)
string concatenation!
96JavaScript Example
- ltHEADgt
- ltTITLEgtJavaScript is fun!lt/TITLEgt
- lt/HEADgt
- ltBODYgt
- ltH3gtI am a web page and here is my namelt/H3gt
- ltSCRIPTgt
- document.write(document.title)
- lt/SCRIPTgt
- ltHRgt
97JavaScript andHTML Comments
- ltSCRIPTgt
- lt!--
- document.write("Hi Dave")
- document.bgColor"BLUE"
- --gt
- lt/SCRIPTgt
HTML comment
98JavaScript Functions
- The keyword function used to define a function
(subroutine) - function add(x,y)
- return(xy)
99JavaScript Events
- JavaScript supports an event handling system.
- You can tell the browser to execute javascript
commands when some event occurs. - Sometimes the resulting value of the command
determines the browser action.
100Simple Event Example
- ltBODY BGCOLORWHITE onUnload"restore()"gt
- ltH5gtHello - I am a very small page!lt/H5gt
- ltSCRIPTgt
- savewidth window.innerWidth
- saveheight window.innerHeight
- function restore()
- window.innerWidthsavewidth
- window.innerHeightsaveheight
-
- // Change the window size to be small
- window.innerWidth300 window.innerHeight50
- document.bgColor'cyan'
- lt/SCRIPTgt
101Buttons
- You can associate buttons with JavaScript events
(buttons in HTML forms)
ltFORMgt ltINPUT TYPEBUTTON VALUE"Don't Press
Me" onClick"alert('now you are in trouble!')
gt lt/FORMgt
102Some Events (a small sample)
- onUnLoad
- onLoad
- onClick
- onMouseUp
- onMouseDown
- onDblClick
- onMouseOver
Window events
Button events
Link events
103Document Object Model
- Naming hierarchy used to access individual
elements of a HTML document. - Netscape D.O.M. is a little different than IE
D.O.M. - Easy to use if you name all entities
- Forms, fields, images, etc.
104DOM example
- ltFORM IDmyform ACTION
- Please Enter Your Age
- ltINPUT TYPETEXT IDage NAMEagegtltBRgt
- And your weight
- ltINPUT TYPETEXT IDweight NAMEweightgtltBRgt
- lt/FORMgt
From javascript you can get at the age input
field as document.myform.age.value
105Form Field Validation
- You can have JavaScript code that makes sure the
user enters valid information. - When the submit button is pressed the script
checks the values of all necessary fields - You can prevent the request from happening.
106Checking Fields
- function checkform()
- if (document.myform.age.value "")
- alert("You need to specify an age")
- return(false)
- else
- return(true)
-
-
-
Needs to return true or false!
107The Form
Needed to prevent the browser from submitting!
- ltFORM METHODGET ACTIONfoo.cgi
- NAMEmyform
- onSubmit"return(checkform())"gt
- AGE ltINPUT TYPETEXT NAMEAgegt
- ltINPUT TYPESUBMITgt
- lt/FORMgt
108Important Note about Form Validation
- It's a good idea to make sure the user fills out
the form before submitting. - Users can bypass your form they can create
requests manually (or their own forms).
109Decision-Making Code
110Outline
- Boolean variables
- How to compare values
- The if structure
- The if else structure
111Boolean Variables
- A Boolean variable is a variable that is able to
hold one of two values - true
- false
- Boolean variables are used to answer simple
questions that we can pose in a program. - If the answer is true, we do something.
- If the answer is false, we do something else.
112Creating Booleans
- var x
- x false
- This means that x will store the value of
false. - Note
- it is not a string
- it is not a number
113Comparing Values
- If we compare two values together, we can
determine what their relationship is. - Once we determine their relationship, we can
store that information using a Boolean. - Assume three variables x, y and z
- z (x lt y)
- If x lt y, then z will be true.
- If x gt y, then z will be false.
114Comparing Values
- We can compare in different ways
- Operator Operation
- lt less than
- lt less than or equal to
- gt greater than
- gt greater than or equal to
- equals
- ! not equals
115Examples
- if x2 and y3, then if
- z (xlty) z will be true
- z (xlty) z will be true
- z (xgty) z will be false
- z (xgty) z will be false
- z (xy) z will be false
- z (x!y) z will be true
116Comparing Strings
- We can use the equals operator () to compare
two strings. - We can check to see if two strings are the same
- name1 Bob
- name2 Fred
- result (name1 name2)
- result (name1 ! name2)
117Logic Operators
- Now that we are able to work with Boolean
variables, we need to be able to deal with
multiple Booleans. - We may need to make multiple comparisons and then
decide, based on the results, what we should do. - This requires using logical operations.
118Logical Operations
- Operator Operation Performed
- AND true if both values are true
- OR true if either value is true
- ! NOT negates the value
- These operations can be used on any two Boolean
values and will result in a Boolean value itself.
119AND Logic Table
- Expression Resulting Value
- truetrue true
- truefalse false
- falsetrue false
- falsefalse false
120OR Logic Table
- Expression Resulting Value
- truetrue true
- truefalse true
- falsetrue true
- falsefalse false
121Putting it together
- The logic tables require two Booleans.
- Since any comparison that we make results in a
Boolean, we can use these comparisons in logic
operations where needed. - These logic operations and Booleans will come in
handy when we have to make decisions.
122The if Statement
- One key decision statement is the if statement.
- The if statement allows us to determine the
value of a Boolean and, based on that value,
either execute or skip some section of code. - This is the easiest way to control which code we
are going to run.
123How if Works
- if (Boolean expression)
- statement
-
- statement
124An if Example
- var number
- numberprompt(Enter a number)
- if (number lt 10)
- document.write(Your number is lt 10)
-
- if (number gt 10)
- document.write(Your number is gt 10)
125The if Example
- For our example
- if the number is less than 10, we get one
response - if the number is greater than 10, we get another
response - if the number is equal to 10, what happens?
126An if else Structure
- The if else structure is similar to an if
structure, except that it has a second part
associated with it. - The else portion catches all of that cases that
are not associated with the if Boolean. - This allows us to cover two different cases in
the same structure.
127The if else Structure
- if (Boolean statement)
- statement
-
-
- else
- statement
-
128An if else Example
- var number
- numberprompt(Please input a number)
- if (number lt 10)
- document.write(Your number is lt 10)
-
- else
- document.write(Your number is gt 10)
129More on if
- if and if else statements are the basic
building blocks to decision-making code. - They are the basic method used to control which
code will be executed and which will be skipped. - This allows the user to input information that
will effect how the program will act.
130Some Possible Problems
- One key problem when dealing with variables is
making sure that you are comparing what you want
to compare. - From the perspective of users entering input, you
should be careful that the user enters in the
correct information. - If you are trying to compare numbers and the user
enters letters, it could cause trouble.
131An Example
- If we try to compare a number entered by the
user, but the user enters a string, then the
comparison will still happen. - You may try to use the number entered by the
user later, but because it is a string, it will
cause errors. - Your results may not turn out to be what you want.
132Checking Input
- We can check input from the user with a function
called isNaN() - This function allows us to determine if the
parameters is NaN. - Now that we can determine if a value is a number,
we will be able to ask the user to re-enter
information that we think is correct.
133Checking Input Example
- var number, test
- numberprompt(Enter a number)
- test isNaN(number)
- if (test)
- document.write(The input was a string)
-
- else
- document.write(The input was a number)
134What about bad input?
- If we receive bad input from the user, we can
warn them that the input is incorrect with an
alert. - An alert will create a pop-up dialog along with
some text. The box will stay on the screen until
they click OK. - This is one way to give the user some information.
135An alert Example
- alert (This is an alert on the screen!)
136End of Lecture