More Javascript Programming

tacitmarigoldInternet and Web Development

Jan 25, 2014 (7 years and 6 months ago)

635 views

More Javascript

Programming

READ and PRACTICE

You will need to try JavaScript for yourself;
try and execute some of these examples
so you understand them


Simply reading the slides and attending the
tutorials will *not* be enough for you to
understand JavaScript


Do *not* leave practice to the last minute


it could take some time to master the
‘fascinating subtleties’ of programming …

DEBUGGING!

In
Firefox
,


Go to
"Tools"


"Web Development"


"JavaScript Console"

The console lists any errors it finds in the page


It accumulates them, so to get just the most recent
errors, press "Clear" and then
"shift
-
Reload"

your page

Errors may be difficult to understand


look at one
at a time


Fix it, clear the JavaScript Console, shift
-
reload, and look
at the next one


Fixing one error may make others go away or make more
show up

Forms

Forms

We use a Form to place input objects on a
web page

The input objects allow the user to interact
with our web page.

A form is required! These objects cannot
be placed on a page without being
contained in a form.


Forms..

The input objects we are concerned
with are:


Textboxes
: for entering text


Buttons
: for initiating an action


Radio Buttons
: for choosing something

<form id="
myform
" action="">


<p>enter your name: <br />



<input type="text"


name="
namebox
"


id="
namebox
"


value="" />



<input type="button"


name="gobutton"


id="gobutton"


value="Who am I?" />



</form>

Form Example

Kompozer

Forms

In
Kompozer

we insert a form using
the Insert menu, then insert the
individual objects we need into the
form.

Events and Event Handlers

Events

Web browsers monitor certain activities
and can react as they occur


When a user presses a button on webpage,
the browser notices this happens and can do
something in response

The activities are
events.

The ones we are concerned with are:


Click
: the element has been clicked


Load
: the page is loaded into the browser

Event handlers

Events provide a way to control *when*
JavaScript code gets executed.


not just letting the browser decide as we’ve
been doing so far


We can then tell the browser to do
something when it notices these events by
using
event handlers

Event handlers

Each event has a
corresponding
event
handler

When the event is detected,
the event handler tells the
browser how to react

Not all event/event handlers
apply to every element

Here are the ones we are
concerned with now.


Event

Event
Handler

Click

onclick

Load

onload

Where do Event Handlers go?

Event handlers belong
within the XHTML
code
,
inside the tag

for the element they
are referring to


<input type="button"
onclick
="
some JS code
">

When this button is clicked, do something


<body
onload
="some JS">

When this html page first loads, do something

In
Kompozer

we select the object and edit its
properties

Event handlers continued

For Example…


<form id="example" action="">


<p>



<input

type="button"




value="
ClickMe
!"




name="button1" id="button1"




onclick
="alert('Hello there');"

/>


</p>

</form>

Event handlers example

<input

type="button"


value="
ClickMe
!"


name="button1" id="button1"


onclick
="alert('Hello there');"

/>

Example

<body
onload="alert('Welcome to this page!!');"

>



<form id="test" action="">


<p>


<input type="button" value="Click Me!"


onclick= "alert('You clicked me!!');"

/>


</p>


</form>



</body>

Event handlers again

The browser constantly monitors the webpage and
notices when certain
events

happen such as pressing
the mouse buttons or typing in text


We can then tell the browser to do something when it
notices these events by using
event handlers

<input type="button"
onclick
="JS statement">

Where do Event Handlers go?

Event handlers belong
within the XHTML
code
,
inside the tag

for the element they
are referring to




<input type="button"
onclick
="some JS">

When this button is clicked, do something




<body
onload
="some JS">

When this html page first loads, do something

Example


event handlers

<!DOCTYPE html PUBLIC "
-
//W3C//DTD XHTML 1.0


Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1
-
strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">


<head>


<title></title>


</head>


<body
onload="alert('Hello
-

onload! Welcome to this page!!');"

>


<form id="test" action="">


<p>


<input type="button" value="Click Me!"


onclick= "alert('Hello
-

Button! You clicked me!!');"

/>


</p>


</form>


</body>

</html>

Notice the matching of quotation
marks… single and double quotes

JS
-
on
-
command

How do we get more than one line of JS to
execute when certain events occur?


Write our own functions

Functions

Function


A group of statements that only get executed when
specifically asked to


A function always has a
name


Always has opening/closing curly brackets
{ }

surrounding
the function *body*


Example








function
addnumbers( )




{





var first = 10;





var second = 3;





var sum = first + second;





alert(sum);





}

Function
body

Function name

Function

<!DOCTYPE html PUBLIC "
-
//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1
-
strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>


<title></title>


<script type="text/javascript">


//<![CDATA[


function addnumbers( )


{


var first = 10;


var second = 3;


var sum = first + second;


alert(sum);


}


//]]>


</script>

</head>

<body>


<form>


<p><input type="button" value="Click me!"
onclick="
addnumbers();
"

/></p>


</form>

</body>

</html>



Example

<!DOCTYPE html PUBLIC "
-
//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1
-
strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head><title></title>


<script type="text/javascript">


//<![CDATA[


function sayhi( )


{


var username = prompt("what's your name?", "");


alert("Hi " + username);


}


function whatcolor( )


{


var usercolor = prompt("what color?", "");


alert("You picked "+usercolor);


}


//]]>


</script>

</head>

<body>


<form id="test" action="">


<p>


<input type="button" value="Pick
-
a
-
color"
onclick="
whatcolor();
"

/>


<input type="button" value="Greet
-
me"
onclick="
sayhi();
"

/>


</p>


</form>

</body>

</html>

Example

Types of functions


Procedure Functions


perform some task, do not return any values


eg
:

alert( )
-

displays an alert


Value Functions


perform some task and return a value

prompt( )


returns the user’s answer

parseInt
( )


returns the extracted integer

Math.random
( )


returns a randomly generated number


includes a "
return
" statement

Example

<!DOCTYPE html PUBLIC "
-
//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1
-
strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>


<title></title>


<script type="text/javascript" src="http://www.cs.usask.ca/base.js"></script>


<script type="text/javascript">


//<![CDATA[


function getnum( )


{


var num = prompt("enter a number", "");


num = parseInt(num);


return num;


}


function add( )


{


var total =
getnum( )

+
getnum( )
;


alert("the sum is " + total);


}


function subtract( )


{


var total =
getnum( )

-

getnum( )
;


alert("the difference is " + total);


}


//]]>


</script>

</head>

<body>


<form id="test" action="">


<p>


<input type="button" value="Addition"
onclick="
add();
"

/>


<input type="button" value="Subtraction"
onclick="
subtract();
"

/>


</p>


</form></body></html>



getnum( ) is a
Value

function
because it returns
a value

calls to getnum( )
use the returned
value in calculation

Using Variables in Functions

Variables defined within a function are limited to
the scope of the function


When the function completes, the variables defined in
the function and their values are discarded.


Variables defined outside the function are called
"global" variables


Variables and their values continue to exist as long as
the page is loaded in the browser.


Can be used to ‘remember’ values, such as a
username.


Using Variables in Functions

Good programming style is to declare global
variables at the very beginning of your
JavaScript code


Declare them inside a <script> element, but not within
a function

Example

<!DOCTYPE html PUBLIC "
-
//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1
-
strict.dtd">

<html
xmlns
="http://www.w3.org/1999/xhtml">

<head>


<title></title>


<script type="text/
javascript
"
src
="http://www.cs.usask.ca/base.js"></script>


<script type="text/
javascript
">


//<![CDATA[


var

total

= 0;


var

subtotal = 10;


function
doMath
( )


{


var

average

= 10;


var

total

= 100;


alert("total = " +
total
);


}


function another( )


{


var

minimum = 0;


total

=
total

+ 50;


alert("total = " +
total
);


alert("average = " +
average
);


}


//]]>


</script>

</head><body
onload
="
doMath
(); another();"></body></html>


what will each alert
display? what are the
contents of the variables
at each point? what error
will occur?

Form elements

Sometimes we wish to refer to form
elements that we have placed on the
page, such as textboxes, buttons, and
radio buttons.


We can refer to each of these elements by ID
or Name


We can view and/or update the properties of
these elements




Form elements

Give meaningful names to your form
elements,


Like you do with variable names, right?


So it will be easier to access them later on

Form elements and "dot
notation"

document.getElementById
(“
IdOfElement
").property





getElementById
(" ") finds a specific element on our webpage
with the unique id placed inside the quotes


We will use this method for accessing textboxes


The textbox must have an ‘id’ defined



<input type="text" name="
answerbox
" id="
answerbox
" />



document.getElementById
(“
answerbox

").value

Form elements and "dot
notation"

document.getElementsByName
("name")[number].property




getElementByIName
(" ") finds a specific element on our webpage
with the name placed inside the quotes


getElementsByName
(" ")[
i
] finds the beginning of a group of
elements (like radio buttons) which share a common name. [
i
]
refers to the specific number of the item (starting counting from 0)



<input type="radio" name="
operation
" id="add" value="+" />



document.getElementsByName
(“
operation
")[2].value



Properties of Form Elements

.value

(all form elements)


Returns the relevant value associated with the object,
such as the content of a text box

.checked

(checkbox, radio button only)


A Boolean value (true or false) of whether the item is
checked or chosen


Used when we want to know if a radio button has been
checked.


Any piece of info that comes from a form is
considered to be
a string
!


if you wish to use information from a form as a number,
you’ll need to parse it before doing any calculations with
it.


document.getElementById("firstbox").value

document.getElementById("secondbox").value

document.getElementById("answerbox").value

document.getElementsByName("operation")[0].checked


document.getElementsByName("operation")[1].checked


document.getElementsByName("operation")[2].checked


document

Accessing form elements in JS

Displaying information on a form

We can use the properties to
display (or put)
information
onto the form


Assign to the value
property

of the element



Put the string “
Hello world!" into the “
mytextarea
” textbox

document.getElementById
("
mytextarea
").
value
=
"Hello world!"



Check the first radio button named “operation” as if the user had
clicked it.

document.getElementsByName
(“operation")[0].
checked
=
"true"
;

<!DOCTYPE html PUBLIC "
-
//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1
-
strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head><title></title><script type="text/javascript" src="http://www.cs.usask.ca/base.js"></script> <script type="text/javascr
ipt
">


//<![CDATA[


function perform( )


{


var total = 0;


var num1 = parseInt(
document.getElementById("firstbox").value
);


var num2 = parseInt(
document.getElementById("secondbox").value
);


if (
document.getElementsByName("operation")[0].checked
)


total = num1 + num2;


else if (
document.getElementsByName("operation")[1].checked
)


total = num1
-

num2;


else if (
document.getElementsByName("operation")[2].checked
)


total = num1 * num2;


document.getElementById("answerbox").value

= total;


}


//]]>


</script>

</head>

<body>


<form id="
myform
" action="">


<p>enter two numbers: <br />


<input type="text" name="
firstbox
" id="
firstbox
" value="" />


<input type="text" name="
secondbox
" id="
secondbox
" value="" /><br /><br />


<input type="radio" name="
operation
" id="add" value="+" />Add<br />


<input type="radio" name="
operation
" id="subtract" value="
-
" />Subtract<br />


<input type="radio" name="
operation
" id="multiply" value="*" />Multiply<br /><br />


<input type="button" name="gobutton" id="gobutton" value="Go!" onclick="perform()" /><br /><br />


<input type="text" name="
answerbox
" id="
answerbox
" /></p>


</form></
body></html>

Example

Example

<!DOCTYPE html PUBLIC "
-
//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>


<meta content="text/html; charset=ISO
-
8859
-
1"


http
-
equiv="content
-
type">


<title>converter</title>


<script type="text/javascript">


function DoFtoC( )

{ var F = parseFloat(document.getElementById("farenheit").value);


var C = (F
-
32)*5/9;


document.getElementById("celsius").value = C; }

function DoCtoF( )

{ var C = parseFloat(document.getElementById("celsius").value);


var F = C*9/5+32;


document.getElementById("farenheit").value = F; }


</script>

</head>

<body>

<form method="get" action="" name="Converter">


<table style="text
-
align: left; width: 682px; height: 88px;" border="1" cellpadding="2" cellspacing="2">


<tr>


<td><input id="farenheit"> degrees F</td>


<td>


<input name="FtoC" value="
--
&gt;" onclick="DoFtoC()" type="button"> <br>


<input name="CtoF" value="&lt;
--
" onclick="DoCtoF()" type="button">


</td>


<td><input id="celsius"> degrees C</td>


</tr>


</table>

</form>

</body>

</html>

Forms and loops

Consider this…

Suppose we wanted to check if any value has
been set on a radio button. We could do it by:

if(
document.getElementsByName
("
itemList
")
[0]
.checked)


// do something with the first selection

else if(
document.getElementsByName
("
itemList
")
[1]
.checked)


// do something with the second selection

else if(
document.getElementsByName
("
itemList
")
[2]
.checked)


// do something with the third selection

else if(
document.getElementsByName
("
itemList
")
[3]
.checked)


// do something with the fourth selection

else


// do something about no item selected

This is very repetitious, when only the 0, 1, 2, 3
changes


Long to type in


Can make errors easily!

Forms and for
-
loops

for
-
loops can be used to process radio
buttons


since all that changes when checking these is
the # of the current element

document.getElementsByName
("
itemList
")
[0]

document.getElementsByName
("
itemList
")
[1]

document.getElementsByName
("
itemList
")
[2]


for
-
loops have a variable that increments
each time through the loop, can use this to
check each element in turn

Example




function item_checked( )


{


var checked_item =
-
1;


for(
i=0; i<4; i=i+1
)


{


if(
document.getElementsByName(
"itemList"
)
[i]
.checked
)


checked_item = i;


}


if (checked_item ==
-
1)


alert ("no item was checked");


return checked_item;


}




Readings


Log on to the online course for more
explanations and examples

Be able to understand


Forms and forms objects


Events and event handlers


Functions



To Know


Event


Event Handler


Onclick

handler


Onload

handler


Function


Procedure Function


Value Function


Variable


Global Variable


Local Variable


parseInt


parseFloat



To Know


Key Terms


Compound statement


getElementById


getElementsByName


Document Hierarchy


Form


Form Elements


Radio Button


Checkbox


Textbox


Value property


Checked property


Javascript

console





Learning More JavaScript or just
practicing?


Try the lessons in the on
-
line class


Try the tutorials at
http://www.w3schools.com/js/

These easy tutorials will take you from raw
beginner to advanced JavaScript guru


highly
recommended!


Google too!


More ….