+ All Categories
Home > Documents > CSC4370/6370: Web Programming Event-driven programs and HTML form elements event-driven programs ...

CSC4370/6370: Web Programming Event-driven programs and HTML form elements event-driven programs ...

Date post: 24-Dec-2015
Category:
Upload: marcus-turner
View: 222 times
Download: 0 times
Share this document with a friend
Popular Tags:
30
CSC4370/6370: Web Programming Event-driven programs and HTML form elements event-driven programs onload, onunload HTML forms & attributes button, text box, text area selection list, radio button, check box, password, hidden, … JavaScript form events properties: name, type, value, … methods: blur(), focus(), click(), … event handlers: onblur(), onfocus(), onchange(), onclick(), … advanced features & techniques windows, timeouts, cookies
Transcript
Page 1: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

CSC43706370 Web Programming

Event-driven programs and HTML form elements event-driven programs

onload onunload HTML forms amp attributes

button text box text area selection list radio button check box password hidden hellip

JavaScript form events properties name type value hellip methods blur() focus() click() hellip event handlers onblur() onfocus() onchange() onclick() hellip

advanced features amp techniques windows timeouts cookies

Event-driven programs

bull with C++ or Java programs are usually serially executed start with main function execute sequentially from first statement may loop or skip sections of code but the program generally proceeds step-by-step

the programmer specifies the sequence in which execution occurs (with some variability due to input values)

there is a beginning and an end to program execution

bull computation within a Web page is rarely serial instead the page reacts to events such as mouse clicks buttons hellip much of JavaScripts utility is in specifying actions that are to occur in the page as a result

of some event

the programmer may have little or no control over when code will (if ever) be executed eg code that reacts to a button click

there is no set sequence the page waits for events and reacts

OnLoad amp OnUnload

the simplest events are when the page is loaded or unloaded

the onload attribute of the ltbodygt tag specifies JavaScript code that is automatically executed when the page is loaded

the onunload attribute similarly specifies JavaScript code that is automatically executed when the browser leaves the page

lthtmlgt ltndash- Csc WebPro form01html --gt

ltheadgt lttitlegtHelloGoodbye pagelttitlegt

ltscript type=textjavascriptgt function Hello() globalName=prompt(Welcome to my page + What is your name)

function Goodbye() alert(So long + globalName + come back real soon) ltscriptgt ltheadgt

ltbody onload=Hello() onunload=Goodbye()gt ltpgtWhatever text appears in the pageltpgt ltbodygtlthtmlgt

view page

HTML forms

bull most event-handling in JavaScript is associated with form elements bull an HTML form is a collection of elements for handling input output and events in

a page

ltform name= FormName id=FormNamegthellipltformgt

bull form elements might includefor input button selection list radio button check box password hellipfor inputoutput text box text area hellip

bull we will also encounter forms when we consider CGI programming a form groups together elements whose contents are submitted together to a server

bull documentforms[ ] is an (associative) array that will contain elements for each form on the webpage using the name associated with the form as the array index

bull Using the dotted syntax we can then access other HTML elements of the form (using their names given to those elements) Recall that HTML pages are stored as a hierarchy of parentchild relationships and this defines the way to access the elements (More examples to come)

HTML forms (cont)

Button Element

lthtmlgt ltndash- CSC webpro form02html --gt ltheadgt lttitlegt Fun with Buttonslttitlegt

ltscript type=textjavascript src=httpwwwcoddcsJSrandomjsgt ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Lucky Number onclick=ldquovar num = RandomInt(1 100) alert(The lucky number for the day is + num) gt ltpgt ltformgt ltbodygtlthtmlgt

bull the simplest form element is a button analogous to a real-world button a click can be used to trigger events

ltinput type=button value=LABEL onclick=JAVASCRIPT_CODE gt

view page

Buttons amp Functionslthtmlgt ltndash- CSC webpro form03html --gt ltheadgt lttitlegtFun with Buttonslttitlegt

ltscript type=textjavascriptgt function Greeting() Results displays a time-sensitive greeting var now = new Date() if (nowgetHours() lt 12) alert(Good morning) else if (nowgetHours() lt 18) alert(Good afternoon) else alert(Good evening) ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Greeting onclick=Greeting() gt ltpgt ltformgt ltbodygtlthtmlgt

for complex tasks we can define function(s) and have the onclick event trigger a function call

view page

Buttons amp Windows

bull alert boxes are fine for displaying short infrequent messages not well-suited for displaying longer formatted text not integrated into the page requires the user to explicitly close the box

QUESTION could we instead use documentwrite

NO -- would overwrite the current page including form elements

bull but could open a new browser window and write there

var OutputWindow = windowopen() open a window and assign a name to that object (first arg is an HREF)

OutputWindowdocumentopen() open that window for writing

OutputWindowdocumentwrite(WHATEVER) write text to that window as before

OutputWindowdocumentclose() close the window

Window Examplelthtmlgt lt-ndash CSC webpro form04html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen() OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

OutputWindowdocumentclose() ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Window Example Refinedlthtmlgt lt-ndash CSC webpro form05html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen( status=0menubar=0height=200width=200) OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

ltscriptgt ltheadgt ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

can have arguments to windowopen

1st arg specifies HREF

2nd arg specifies internal name

3rd arg specifies window properties (eg size)

view page

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 2: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Event-driven programs

bull with C++ or Java programs are usually serially executed start with main function execute sequentially from first statement may loop or skip sections of code but the program generally proceeds step-by-step

the programmer specifies the sequence in which execution occurs (with some variability due to input values)

there is a beginning and an end to program execution

bull computation within a Web page is rarely serial instead the page reacts to events such as mouse clicks buttons hellip much of JavaScripts utility is in specifying actions that are to occur in the page as a result

of some event

the programmer may have little or no control over when code will (if ever) be executed eg code that reacts to a button click

there is no set sequence the page waits for events and reacts

OnLoad amp OnUnload

the simplest events are when the page is loaded or unloaded

the onload attribute of the ltbodygt tag specifies JavaScript code that is automatically executed when the page is loaded

the onunload attribute similarly specifies JavaScript code that is automatically executed when the browser leaves the page

lthtmlgt ltndash- Csc WebPro form01html --gt

ltheadgt lttitlegtHelloGoodbye pagelttitlegt

ltscript type=textjavascriptgt function Hello() globalName=prompt(Welcome to my page + What is your name)

function Goodbye() alert(So long + globalName + come back real soon) ltscriptgt ltheadgt

ltbody onload=Hello() onunload=Goodbye()gt ltpgtWhatever text appears in the pageltpgt ltbodygtlthtmlgt

view page

HTML forms

bull most event-handling in JavaScript is associated with form elements bull an HTML form is a collection of elements for handling input output and events in

a page

ltform name= FormName id=FormNamegthellipltformgt

bull form elements might includefor input button selection list radio button check box password hellipfor inputoutput text box text area hellip

bull we will also encounter forms when we consider CGI programming a form groups together elements whose contents are submitted together to a server

bull documentforms[ ] is an (associative) array that will contain elements for each form on the webpage using the name associated with the form as the array index

bull Using the dotted syntax we can then access other HTML elements of the form (using their names given to those elements) Recall that HTML pages are stored as a hierarchy of parentchild relationships and this defines the way to access the elements (More examples to come)

HTML forms (cont)

Button Element

lthtmlgt ltndash- CSC webpro form02html --gt ltheadgt lttitlegt Fun with Buttonslttitlegt

ltscript type=textjavascript src=httpwwwcoddcsJSrandomjsgt ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Lucky Number onclick=ldquovar num = RandomInt(1 100) alert(The lucky number for the day is + num) gt ltpgt ltformgt ltbodygtlthtmlgt

bull the simplest form element is a button analogous to a real-world button a click can be used to trigger events

ltinput type=button value=LABEL onclick=JAVASCRIPT_CODE gt

view page

Buttons amp Functionslthtmlgt ltndash- CSC webpro form03html --gt ltheadgt lttitlegtFun with Buttonslttitlegt

ltscript type=textjavascriptgt function Greeting() Results displays a time-sensitive greeting var now = new Date() if (nowgetHours() lt 12) alert(Good morning) else if (nowgetHours() lt 18) alert(Good afternoon) else alert(Good evening) ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Greeting onclick=Greeting() gt ltpgt ltformgt ltbodygtlthtmlgt

for complex tasks we can define function(s) and have the onclick event trigger a function call

view page

Buttons amp Windows

bull alert boxes are fine for displaying short infrequent messages not well-suited for displaying longer formatted text not integrated into the page requires the user to explicitly close the box

QUESTION could we instead use documentwrite

NO -- would overwrite the current page including form elements

bull but could open a new browser window and write there

var OutputWindow = windowopen() open a window and assign a name to that object (first arg is an HREF)

OutputWindowdocumentopen() open that window for writing

OutputWindowdocumentwrite(WHATEVER) write text to that window as before

OutputWindowdocumentclose() close the window

Window Examplelthtmlgt lt-ndash CSC webpro form04html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen() OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

OutputWindowdocumentclose() ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Window Example Refinedlthtmlgt lt-ndash CSC webpro form05html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen( status=0menubar=0height=200width=200) OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

ltscriptgt ltheadgt ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

can have arguments to windowopen

1st arg specifies HREF

2nd arg specifies internal name

3rd arg specifies window properties (eg size)

view page

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 3: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

OnLoad amp OnUnload

the simplest events are when the page is loaded or unloaded

the onload attribute of the ltbodygt tag specifies JavaScript code that is automatically executed when the page is loaded

the onunload attribute similarly specifies JavaScript code that is automatically executed when the browser leaves the page

lthtmlgt ltndash- Csc WebPro form01html --gt

ltheadgt lttitlegtHelloGoodbye pagelttitlegt

ltscript type=textjavascriptgt function Hello() globalName=prompt(Welcome to my page + What is your name)

function Goodbye() alert(So long + globalName + come back real soon) ltscriptgt ltheadgt

ltbody onload=Hello() onunload=Goodbye()gt ltpgtWhatever text appears in the pageltpgt ltbodygtlthtmlgt

view page

HTML forms

bull most event-handling in JavaScript is associated with form elements bull an HTML form is a collection of elements for handling input output and events in

a page

ltform name= FormName id=FormNamegthellipltformgt

bull form elements might includefor input button selection list radio button check box password hellipfor inputoutput text box text area hellip

bull we will also encounter forms when we consider CGI programming a form groups together elements whose contents are submitted together to a server

bull documentforms[ ] is an (associative) array that will contain elements for each form on the webpage using the name associated with the form as the array index

bull Using the dotted syntax we can then access other HTML elements of the form (using their names given to those elements) Recall that HTML pages are stored as a hierarchy of parentchild relationships and this defines the way to access the elements (More examples to come)

HTML forms (cont)

Button Element

lthtmlgt ltndash- CSC webpro form02html --gt ltheadgt lttitlegt Fun with Buttonslttitlegt

ltscript type=textjavascript src=httpwwwcoddcsJSrandomjsgt ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Lucky Number onclick=ldquovar num = RandomInt(1 100) alert(The lucky number for the day is + num) gt ltpgt ltformgt ltbodygtlthtmlgt

bull the simplest form element is a button analogous to a real-world button a click can be used to trigger events

ltinput type=button value=LABEL onclick=JAVASCRIPT_CODE gt

view page

Buttons amp Functionslthtmlgt ltndash- CSC webpro form03html --gt ltheadgt lttitlegtFun with Buttonslttitlegt

ltscript type=textjavascriptgt function Greeting() Results displays a time-sensitive greeting var now = new Date() if (nowgetHours() lt 12) alert(Good morning) else if (nowgetHours() lt 18) alert(Good afternoon) else alert(Good evening) ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Greeting onclick=Greeting() gt ltpgt ltformgt ltbodygtlthtmlgt

for complex tasks we can define function(s) and have the onclick event trigger a function call

view page

Buttons amp Windows

bull alert boxes are fine for displaying short infrequent messages not well-suited for displaying longer formatted text not integrated into the page requires the user to explicitly close the box

QUESTION could we instead use documentwrite

NO -- would overwrite the current page including form elements

bull but could open a new browser window and write there

var OutputWindow = windowopen() open a window and assign a name to that object (first arg is an HREF)

OutputWindowdocumentopen() open that window for writing

OutputWindowdocumentwrite(WHATEVER) write text to that window as before

OutputWindowdocumentclose() close the window

Window Examplelthtmlgt lt-ndash CSC webpro form04html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen() OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

OutputWindowdocumentclose() ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Window Example Refinedlthtmlgt lt-ndash CSC webpro form05html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen( status=0menubar=0height=200width=200) OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

ltscriptgt ltheadgt ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

can have arguments to windowopen

1st arg specifies HREF

2nd arg specifies internal name

3rd arg specifies window properties (eg size)

view page

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 4: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

HTML forms

bull most event-handling in JavaScript is associated with form elements bull an HTML form is a collection of elements for handling input output and events in

a page

ltform name= FormName id=FormNamegthellipltformgt

bull form elements might includefor input button selection list radio button check box password hellipfor inputoutput text box text area hellip

bull we will also encounter forms when we consider CGI programming a form groups together elements whose contents are submitted together to a server

bull documentforms[ ] is an (associative) array that will contain elements for each form on the webpage using the name associated with the form as the array index

bull Using the dotted syntax we can then access other HTML elements of the form (using their names given to those elements) Recall that HTML pages are stored as a hierarchy of parentchild relationships and this defines the way to access the elements (More examples to come)

HTML forms (cont)

Button Element

lthtmlgt ltndash- CSC webpro form02html --gt ltheadgt lttitlegt Fun with Buttonslttitlegt

ltscript type=textjavascript src=httpwwwcoddcsJSrandomjsgt ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Lucky Number onclick=ldquovar num = RandomInt(1 100) alert(The lucky number for the day is + num) gt ltpgt ltformgt ltbodygtlthtmlgt

bull the simplest form element is a button analogous to a real-world button a click can be used to trigger events

ltinput type=button value=LABEL onclick=JAVASCRIPT_CODE gt

view page

Buttons amp Functionslthtmlgt ltndash- CSC webpro form03html --gt ltheadgt lttitlegtFun with Buttonslttitlegt

ltscript type=textjavascriptgt function Greeting() Results displays a time-sensitive greeting var now = new Date() if (nowgetHours() lt 12) alert(Good morning) else if (nowgetHours() lt 18) alert(Good afternoon) else alert(Good evening) ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Greeting onclick=Greeting() gt ltpgt ltformgt ltbodygtlthtmlgt

for complex tasks we can define function(s) and have the onclick event trigger a function call

view page

Buttons amp Windows

bull alert boxes are fine for displaying short infrequent messages not well-suited for displaying longer formatted text not integrated into the page requires the user to explicitly close the box

QUESTION could we instead use documentwrite

NO -- would overwrite the current page including form elements

bull but could open a new browser window and write there

var OutputWindow = windowopen() open a window and assign a name to that object (first arg is an HREF)

OutputWindowdocumentopen() open that window for writing

OutputWindowdocumentwrite(WHATEVER) write text to that window as before

OutputWindowdocumentclose() close the window

Window Examplelthtmlgt lt-ndash CSC webpro form04html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen() OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

OutputWindowdocumentclose() ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Window Example Refinedlthtmlgt lt-ndash CSC webpro form05html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen( status=0menubar=0height=200width=200) OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

ltscriptgt ltheadgt ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

can have arguments to windowopen

1st arg specifies HREF

2nd arg specifies internal name

3rd arg specifies window properties (eg size)

view page

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 5: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

bull documentforms[ ] is an (associative) array that will contain elements for each form on the webpage using the name associated with the form as the array index

bull Using the dotted syntax we can then access other HTML elements of the form (using their names given to those elements) Recall that HTML pages are stored as a hierarchy of parentchild relationships and this defines the way to access the elements (More examples to come)

HTML forms (cont)

Button Element

lthtmlgt ltndash- CSC webpro form02html --gt ltheadgt lttitlegt Fun with Buttonslttitlegt

ltscript type=textjavascript src=httpwwwcoddcsJSrandomjsgt ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Lucky Number onclick=ldquovar num = RandomInt(1 100) alert(The lucky number for the day is + num) gt ltpgt ltformgt ltbodygtlthtmlgt

bull the simplest form element is a button analogous to a real-world button a click can be used to trigger events

ltinput type=button value=LABEL onclick=JAVASCRIPT_CODE gt

view page

Buttons amp Functionslthtmlgt ltndash- CSC webpro form03html --gt ltheadgt lttitlegtFun with Buttonslttitlegt

ltscript type=textjavascriptgt function Greeting() Results displays a time-sensitive greeting var now = new Date() if (nowgetHours() lt 12) alert(Good morning) else if (nowgetHours() lt 18) alert(Good afternoon) else alert(Good evening) ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Greeting onclick=Greeting() gt ltpgt ltformgt ltbodygtlthtmlgt

for complex tasks we can define function(s) and have the onclick event trigger a function call

view page

Buttons amp Windows

bull alert boxes are fine for displaying short infrequent messages not well-suited for displaying longer formatted text not integrated into the page requires the user to explicitly close the box

QUESTION could we instead use documentwrite

NO -- would overwrite the current page including form elements

bull but could open a new browser window and write there

var OutputWindow = windowopen() open a window and assign a name to that object (first arg is an HREF)

OutputWindowdocumentopen() open that window for writing

OutputWindowdocumentwrite(WHATEVER) write text to that window as before

OutputWindowdocumentclose() close the window

Window Examplelthtmlgt lt-ndash CSC webpro form04html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen() OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

OutputWindowdocumentclose() ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Window Example Refinedlthtmlgt lt-ndash CSC webpro form05html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen( status=0menubar=0height=200width=200) OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

ltscriptgt ltheadgt ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

can have arguments to windowopen

1st arg specifies HREF

2nd arg specifies internal name

3rd arg specifies window properties (eg size)

view page

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 6: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Button Element

lthtmlgt ltndash- CSC webpro form02html --gt ltheadgt lttitlegt Fun with Buttonslttitlegt

ltscript type=textjavascript src=httpwwwcoddcsJSrandomjsgt ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Lucky Number onclick=ldquovar num = RandomInt(1 100) alert(The lucky number for the day is + num) gt ltpgt ltformgt ltbodygtlthtmlgt

bull the simplest form element is a button analogous to a real-world button a click can be used to trigger events

ltinput type=button value=LABEL onclick=JAVASCRIPT_CODE gt

view page

Buttons amp Functionslthtmlgt ltndash- CSC webpro form03html --gt ltheadgt lttitlegtFun with Buttonslttitlegt

ltscript type=textjavascriptgt function Greeting() Results displays a time-sensitive greeting var now = new Date() if (nowgetHours() lt 12) alert(Good morning) else if (nowgetHours() lt 18) alert(Good afternoon) else alert(Good evening) ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Greeting onclick=Greeting() gt ltpgt ltformgt ltbodygtlthtmlgt

for complex tasks we can define function(s) and have the onclick event trigger a function call

view page

Buttons amp Windows

bull alert boxes are fine for displaying short infrequent messages not well-suited for displaying longer formatted text not integrated into the page requires the user to explicitly close the box

QUESTION could we instead use documentwrite

NO -- would overwrite the current page including form elements

bull but could open a new browser window and write there

var OutputWindow = windowopen() open a window and assign a name to that object (first arg is an HREF)

OutputWindowdocumentopen() open that window for writing

OutputWindowdocumentwrite(WHATEVER) write text to that window as before

OutputWindowdocumentclose() close the window

Window Examplelthtmlgt lt-ndash CSC webpro form04html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen() OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

OutputWindowdocumentclose() ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Window Example Refinedlthtmlgt lt-ndash CSC webpro form05html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen( status=0menubar=0height=200width=200) OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

ltscriptgt ltheadgt ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

can have arguments to windowopen

1st arg specifies HREF

2nd arg specifies internal name

3rd arg specifies window properties (eg size)

view page

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 7: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Buttons amp Functionslthtmlgt ltndash- CSC webpro form03html --gt ltheadgt lttitlegtFun with Buttonslttitlegt

ltscript type=textjavascriptgt function Greeting() Results displays a time-sensitive greeting var now = new Date() if (nowgetHours() lt 12) alert(Good morning) else if (nowgetHours() lt 18) alert(Good afternoon) else alert(Good evening) ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Greeting onclick=Greeting() gt ltpgt ltformgt ltbodygtlthtmlgt

for complex tasks we can define function(s) and have the onclick event trigger a function call

view page

Buttons amp Windows

bull alert boxes are fine for displaying short infrequent messages not well-suited for displaying longer formatted text not integrated into the page requires the user to explicitly close the box

QUESTION could we instead use documentwrite

NO -- would overwrite the current page including form elements

bull but could open a new browser window and write there

var OutputWindow = windowopen() open a window and assign a name to that object (first arg is an HREF)

OutputWindowdocumentopen() open that window for writing

OutputWindowdocumentwrite(WHATEVER) write text to that window as before

OutputWindowdocumentclose() close the window

Window Examplelthtmlgt lt-ndash CSC webpro form04html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen() OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

OutputWindowdocumentclose() ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Window Example Refinedlthtmlgt lt-ndash CSC webpro form05html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen( status=0menubar=0height=200width=200) OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

ltscriptgt ltheadgt ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

can have arguments to windowopen

1st arg specifies HREF

2nd arg specifies internal name

3rd arg specifies window properties (eg size)

view page

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 8: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Buttons amp Windows

bull alert boxes are fine for displaying short infrequent messages not well-suited for displaying longer formatted text not integrated into the page requires the user to explicitly close the box

QUESTION could we instead use documentwrite

NO -- would overwrite the current page including form elements

bull but could open a new browser window and write there

var OutputWindow = windowopen() open a window and assign a name to that object (first arg is an HREF)

OutputWindowdocumentopen() open that window for writing

OutputWindowdocumentwrite(WHATEVER) write text to that window as before

OutputWindowdocumentclose() close the window

Window Examplelthtmlgt lt-ndash CSC webpro form04html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen() OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

OutputWindowdocumentclose() ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Window Example Refinedlthtmlgt lt-ndash CSC webpro form05html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen( status=0menubar=0height=200width=200) OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

ltscriptgt ltheadgt ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

can have arguments to windowopen

1st arg specifies HREF

2nd arg specifies internal name

3rd arg specifies window properties (eg size)

view page

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 9: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Window Examplelthtmlgt lt-ndash CSC webpro form04html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen() OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

OutputWindowdocumentclose() ltscriptgt ltheadgt

ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Window Example Refinedlthtmlgt lt-ndash CSC webpro form05html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen( status=0menubar=0height=200width=200) OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

ltscriptgt ltheadgt ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

can have arguments to windowopen

1st arg specifies HREF

2nd arg specifies internal name

3rd arg specifies window properties (eg size)

view page

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 10: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Window Example Refinedlthtmlgt lt-ndash CSC webpro form05html --gt ltheadgt lttitlegt Fun with Buttons lttitlegt ltscript type=textjavascriptgt function Help() Results displays a help message in a separate window var OutputWindow = windowopen( status=0menubar=0height=200width=200) OutputWindowdocumentopen()

OutputWindowdocumentwrite(This might be a context- + sensitive help message depending on the + application and state of the page)

ltscriptgt ltheadgt ltbodygt ltform name=ButtonForm id=ButtonForm action=gt ltpgt ltinput type=button value=Click for Help onclick=Help() gt ltpgt ltformgt ltbodygtlthtmlgt

can have arguments to windowopen

1st arg specifies HREF

2nd arg specifies internal name

3rd arg specifies window properties (eg size)

view page

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 11: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Text Boxes

bull a text box allows for user input (and could also be used for output) unlike prompt user input persists on the page amp can be edited

ltinput type=text id=BOX_NAME name=BOX_NAME hellip gt

optional attributes size width of the box (number of characters)value initial contents of the box

JavaScript code can access the contents in the example below as documentforms[BoxForm]userNamevalue

lthtmlgt lt-ndash CSC webpro form06html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=userNamegtEnter your name hereltlabelgt ltinput type=text name=userName id=userName size=12 value= gt ltbr gtltbr gt ltinput type=button value=Click Me onclick=alert(Thanks + documentforms[BoxForm]userNamevalue + I needed that) gt ltpgt ltformgt ltbodygtlthtmlgt

view page

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 12: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

ReadWrite Text Boxes

bull similarly can change the contents with an assignment Note the contents are raw text no HTML formattingAlso contents are accessed as a string must parseFloat or parseInt if want a

numberlthtmlgt lt-ndash CSC webpro form07html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=numbergtEnter a number hereltlabelgt ltinput type=text size=12 name=number id=number value=2 gt ltbr gtltbr gt ltinput type=button value=Double onclick=documentforms[BoxForm]numbervalue= parseFloat(documentforms[BoxForm]numbervalue) 2 gt ltpgt ltformgt ltbodygtlthtmlgt

view page

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 13: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Text Box Events

onchange triggered when the contents of the box are changed

onfocus triggered when the mouse clicks in the box

blur() removes focus

lthtmlgt lt-ndash CSC webpro form08html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) Assumes tempInFahr is a number (degrees Fahrenheit) Returns corresponding temperature in degrees Celsius return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=documentforms[BoxForm]Celsiusvalue = FahrToCelsius(parseFloat(documentforms[lsquoBoxFormrsquo]Fahrvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 14: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Text Box Validation

bull what if the user enters a non-number in the Fahrenheit box

bull solution have the text box validate its own contents start with legal value (or an empty text box) at onchange verify that new value is legal (otherwise reset)

the verifyjs library defines several functions for validating text boxes (httpcoddcsgsueduJS)

function VerifyNum(textBox) Assumes textBox is a text box Returns true if textBox contains a number else false + alert var boxValue = parseFloat(textBoxvalue) if ( isNaN(boxValue) ) isNaN function alert(You must enter a number value) textBoxvalue = return false return true

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 15: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Validation Examplelthtmlgt lt-ndash CSC webpro form09html --gt

ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=ldquohttpcoddhellipcomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgt ltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name=Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element documentforms[lsquoBoxFormrsquo]Celsiusvalue = FahrToCelsius(parseFloat(thisvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=blur() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 16: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Text Areas

bull a TEXT box is limited to one line of inputoutput

bull a TEXTAREA is similar to a text box in functionality but can specify any number of rows and columns

lttextarea name=TextAreaName rows=NumRows cols=NumColsgtInitial Textlttextareagt

Note unlike a text box a TEXTAREA has a separate closing taginitial contents of the TEXTAREA appear between the tags

as with a text box no HTML formatting of TEXTAREA contents in performed

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 17: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

TEXTAREA Examplelthtmlgt lt-ndash CSC webpro form10html --gt ltheadgt lttitlegt Fun with Textareas lttitlegt ltscript type=textjavascript src=httpwwwcoddJSverifyjsgt ltscriptgt ltscript type=textjavascriptgt function Table(low high power) Results displays table of numbers between low amp high raised to power var message = i i^ + power + n-------n for (var i = low i lt= high i++) message = message + i + + Mathpow(i power) + n documentforms[AreaForm]Outputvalue = message ltscriptgt ltheadgt ltbodygt ltform name=AreaForm id=AreaForm action=gt ltdiv style=text-align centergt ltpgt Show the numbers from ltinput type=text name=lowRange size=4

value=1 onchange=VerifyInt(this) gt to ltinput type=text name=highRange size=ldquo4rdquo value=ldquo10rdquo onchange=VerifyInt(this) gt raised to the power of ltinput type=text name=power size=3 value=2 onchange=VerifyInt(this) gt ltbr gt ltbr gt ltinput type=button value=Generate Table onclick=Table(parseFloat(documentforms[AreaForm]lowRangevalue) parseFloat(documentforms[AreaForm]highRangevalue) parseFloat(documentforms[AreaForm]powervalue)) gt ltbr gt ltbr gt lttextarea name=Output rows=20 cols=15gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 18: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

bull So far we have been accessing data input fields by giving them names and using the ldquodottedrdquo names from the Document Object Model tree structure

bull What if someone modifies the HTML documentbull Then all those multiply referenced items can no longer be accessed if the name of the form changes

bull A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the ldquoidrdquo attibute) and use the JavaScript getElementById method

bull In practice every item (like input boxes textboxes etc) should be given both a name and an id The ldquonamerdquo is used ifwhen information is submitted to the server and the ldquoidrdquo is what is used on the client to identify that HTML element (Typically the name and id are given the same value)

Better (and easier) methods to access data

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 19: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Using getElementByIdlthtmlgt lt-ndash CSC webpro form09html --gt ltheadgt lttitlegt Fun with Text Boxes lttitlegt ltscript type=textjavascript src=httpwwwcoddcscomp519JSverifyjsgt ltscriptgt

ltscript type=textjavascriptgt function FahrToCelsius(tempInFahr) return (59)(tempInFahr - 32) ltscriptgt ltheadgt

ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtltlabel for=FahrgtTemperature in Fahrenheitltlabelgt ltinput type=text name =Fahr id=Fahr size=10 value=0 onchange=if (VerifyNum(this)) this refers to current element var F=documentgetElementById(Fahr) var C=documentgetElementById(Celsius) Cvalue = FahrToCelsius(parseFloat(Fvalue)) gt ampnbsp ltttgt----gtltttgt ampnbsp ltinput type=text name=Celsius id=Celsius size=10 value= onfocus=getElementById(Fahr)focus() gt in Celsius ltpgt ltformgt ltbodygtlthtmlgt

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 20: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

bullA check box is a list of items one or more of which can be selected

bullThis is easy to create in HTML simply using the ldquocheckboxrdquo input item

bullGive the checkbox a name and use this for each of the elements in the checkbox list (with a separate value for each one)

bullThe set of checkboxes are stored internally as an array

Check boxes

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 21: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Check buttonslthtmlgt lt-ndash CSC webpro form16html --gt ltheadgt lttitlegt Check Boxes lttitlegt ltscript type=textjavascriptgt function processCB() var boxes = documentforms[BoxForm]cblength var s= for (var i = 0 i lt boxes i++) if (documentforms[BoxForm]cb[i]checked) s = s + documentforms[BoxForm]cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxForm action=gt ltpgtWhich of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox id=Robbie name=cb value=Robbie Williams gtltlabel for=RobbiegtRobbie Williamsltlabelgtltbrgt ltbrgt ltinput type=button value=Done onclick=processCB() gt ltpgt ltformgt

ltbodygtlthtmlgt

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 22: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

lthtmlgt lt-- CSC webpro form16ahtml --gt ltheadgt lttitlegt Using checkboxes lttitlegt ltscript type=textjavascriptgt function processCB() var s= var cb=documentforms[BoxForm]elements[cb] for (var i = 0 i lt cblength i++) if (cb[i]checked) s = s + cb[i]value + if (s == ) s = nothing alert(You selected + s) ltscriptgt ltheadgt ltbodygt ltform name=BoxForm id=BoxFormgt ltpgt Which of these things is unavoidable in life (select one or more)ltbrgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Death value=Death gt ltlabel for=DeathgtDeathltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Taxes value=Taxes gt ltlabel for=TaxesgtTaxesltlabelgtltbrgt ampnbsp ltinput type=checkbox name=cb id=Robbie value=Robbie Williams gt ltlabel for=RobbiegtRobbie Williamsltlabelgt ltbrgt ltbrgt ltinput type=button value=Done onclick=processCB()gt ltpgt ltformgt ltbodygt lthtmlgt

Check buttons (using a slightly different method)

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 23: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Radio buttons

bull Radio buttons are similar to check boxes but only one of them can be selected at any time

bull They are defined by ltinput type=radiogt tags (similar to the checkbox tags in the previous example with similar properties) and accessed in the same manner

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 24: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

bullTypically forms are used when information is submitted to a serverbullThis involves either having a ldquosubmitrdquo button in the form or using JavaScript to submit the form by calling the submit functionbullWhen you submit the form you must specify an ldquoactionrdquo to be performed (this is usually a script of some type such as a PHP script) and a method of sending the information (either ldquogetrdquo or ldquopostrdquo) bullWe will see more of this laterhellip

Form submission

lthtmlgt lt-- CSC webpro form17html 13102011 --gt ltheadgt lttitlegt Submitting information lttitlegt ltheadgt ltbodygt ltform name=Information id=Information action=process_formphp

method=postgt

ltpgtltbrgt ltlabel for=PersongtPlease enter your nameltlabelgt ltinput type=text size=30 name=Person id=Person gt ltbrgtltbrgt Please select your gender ltbrgt ltinput type=radio name=sex id=female value=femalegt ltlabel for=femalegtFemaleltlabelgt ltbrgt ltinput type=radio name=sex id=male value=male gt ltlabel for=malegtMaleltlabelgt ltbr gt ltinput type=submit value=Submit gt ltpgt ltformgt ltbodygt lthtmlgt

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 25: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

JavaScript amp Timeouts

bull the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted MillisecondsUntilExecution)

bull example forward link to a moved pagelthtmlgt ltndash- CSC webpro form13html 13102006 --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function Move() Results sets the current page contents to be newhomehtml selflocationhref = newhomehtml ltscriptgt ltheadgt

ltbody onload=setTimeout(Move() 3000)gt ltpgt This page has moved to lta

href=newhomehtmlgtnewhomehtmlltagt ltpgt ltbodygtlthtmlgt

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 26: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

lthtmlgt ltndash- CSC webpro form14html --gt ltheadgt lttitlegt Fun with Timeouts lttitlegt ltscript type=textjavascriptgt function timeSince() Assumes documentforms[CountForm]countdown exists in the page Results every second recursively writes current countdown in the box CODE FOR DETERMINING NUMBER OF DAYS HOURS MINUTES AND SECONDS UNTIL GRADUATION (see the file for this code)

documentforms[CountForm]countdownvalue= days + days + hours + hours + minutes + minutes and + secs + seconds

setTimeout(timeSince() 1000) ltscriptgt ltheadgt

ltbody onload=timeSince()gt ltform name=CountForm id=CountForm action=gt ltdiv style=text-align centergt ltpgt Countdown to Graduation 2011 ltbr gt lttextarea name=countdown id=countdown rows=4 cols=15

style=font-family Courier onfocus=blur()gtlttextareagt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Another Timeout Example

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 27: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

Cookies amp JavaScript

bull recall that cookies are data files stored on the client machine can be accessed andor modified by the server can also be accessed andor modified directly by JavaScript code in a page

bull potential applications e-commerce remember customer name past visitspurchases password hellip tutorials remember past experience performance on quizzes hellip games remember high score best times hellip

bull each Web page can have its own cookie documentcookie is a string of attribute=value pairs separated by

userName=bjenascore=100expires=Mon 21-Feb-01 000001 GMT

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 28: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

function getCookie(Attribute) Assumes Attribute is a string Results gets the value stored under the Attribute if (documentcookieindexOf(Attribute+=) == -1) return else var begin = documentcookieindexOf(Attribute+=) + Attributelength+1

var end = documentcookieindexOf( begin) if (end == -1) end = documentcookielength return unescape(documentcookiesubstring(begin end))

function setCookie(Attribute Value) Assumes Attribute is a string Results stores Value under the name Attribute expires in 30 days var ExpireDate = new Date() ExpireDatesetTime(ExpireDategetTime() + (302436001000)) documentcookie = Attribute + = + escape(Value) + expires= + ExpireDatetoGMTString()

function delCookie(Attribute) Assumes Attribute is a string Results removes the cookie value under the name Attribute var now = new Date() documentcookie = Attribute + = expires= + nowtoGMTString()

cookiejs

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 29: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

lthtmlgt ltndash CSC webpro form15html --gt

ltheadgt lttitlegt Fun with Cookies lttitlegt ltscript type=textjavascript src=httpwwwcsclivacuk~martinteachingcomp519JScookiejsgt ltscriptgt

ltscript type=textjavascriptgt function Greeting() Results displays greeting using cookie visitCount = getCookie(visits) if (visitCount == ) alert(Welcome to my page newbie) setCookie(visits 1) else visitCount = parseFloat(visitCount)+1 alert(Welcome back for visit + visitCount) setCookie(visits visitCount) ltscriptgt ltheadgt

ltbody onload=Greeting()gt ltpgt Here is the stuff in my page ltpgt ltform name=ClearForm id=ClearForm action=gt ltdiv style=text-align centergt ltpgt ltinput type=button value=Clear Cookie

onclick=delCookie(visits) gt ltpgt ltdivgt ltformgt ltbodygtlthtmlgt

Cookie Example

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen
Page 30: CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,

A recap of things we have seen

Event-driven programs and HTML form elements

event-driven programsonload onunload

HTML forms amp attributesbutton text box text areaselection list radio button check box password hidden hellip

JavaScript form eventsproperties name type value id hellip methods blur() focus() click() hellipevent handlers onblur() onfocus() onchange() onclick()

advanced features amp techniqueswindows timeouts cookies

  • Slide 1
  • Event-driven programs
  • OnLoad amp OnUnload
  • HTML forms
  • HTML forms (cont)
  • Button Element
  • Buttons amp Functions
  • Buttons amp Windows
  • Window Example
  • Window Example Refined
  • Text Boxes
  • ReadWrite Text Boxes
  • Text Box Events
  • Text Box Validation
  • Validation Example
  • Text Areas
  • TEXTAREA Example
  • Better (and easier) methods to access data
  • Using getElementById
  • Check boxes
  • Check buttons
  • Check buttons (using a slightly different method)
  • Radio buttons
  • Form submission
  • JavaScript amp Timeouts
  • Another Timeout Example
  • Cookies amp JavaScript
  • cookiejs
  • Cookie Example
  • A recap of things we have seen

Recommended