+ All Categories
Home > Documents > ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Date post: 30-Dec-2015
Category:
Upload: maisie-cook
View: 24 times
Download: 4 times
Share this document with a friend
Description:
ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2. Dr. Faisal Al-Qaed. Note using ID attributes. - PowerPoint PPT Presentation
67
ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2 Dr. Faisal Al-Qaed
Transcript
Page 1: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

ITCS373: Internet Technology

Client Side Processing using JavaScript – Part 2

Dr. Faisal Al-Qaed

Page 2: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Note using ID attributes As you have experienced before, using

document.write will overwrite the current webpage by new one, to avoid this issue, you can add id attributes in your HTML tags (i.e. span, div, b, i, etc) and then follow these simple steps to write in your id section: Add id attribute to your tag i.e. <div id=“mytxt”></div> In your JavaScript code, you can displays any text or

html contents like formatting text, tables, images, forms, etc as follows:

mytxt.innerHTML=“<b>welcome</b>”; document.getElementById(“mytxt”).innerHTML

=“<b>welcome</b>”;

Page 3: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Example

<script type="text/javascript"> function changeText3(){ var oldHTML = document.getElementById('para').innerHTML; var newHTML = "<span style='color:#ffffff'>" + oldHTML + "</span>"; document.getElementById('para').innerHTML = newHTML; } </script> <p id='para'>Welcome to the site <b id='boldStuff3'>Bold</b> </p> <form><input type='button' onclick='changeText3()' value='Change Text'/> </form>

Page 4: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Show/Hide Div Example<html><head><script language-'javascript'><!--function hideMe(){

document.getElementById('d1').style.visibility='hidden';}function showMe(){

document.getElementById('d1').style.visibility='visible';}--> </script></head><body>

<a href='javascript:hideMe()'>Hide Score</a> <a href='javascript:showMe()'>Show Score</a>

<div id='d1'><h1>BestScore:</h1><h3>97 seconds</h3></div></body></html>

Page 5: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Collapsible Div

<a href="javascript:;" onmousedown="toggleDiv('mydiv');">Toggle Div Visibility</a>

<script language="javascript">  function toggleDiv(divid){    if(document.getElementById(divid).style.display == 'none')       document.getElementById(divid).style.display = 'block';

else       document.getElementById(divid).style.display =

'none';  }

</script>

<div id=‘mydiv’>My Div Section</div>

Page 6: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Use Div as Alert Message: Example<html><head><script language='javascript'>function showDiv(){document.getElementById("myDiv").style.top=100;document.getElementById("myDiv").style.left=100;}</script></head><body onload='showDiv()'> <h1>Welcome to Div Control</h1><h1>Try this example to learn How</h1><h1>to position Div</h1><h1>Click on Show and Hide</h1><div id="myDiv" style="position:absolute;border:groove;width:250px;height:100px;background-

color:yellow" ><h3>Alert Message</h3></div>

<h1 onClick="javascript:document.getElementById('myDiv').style.display='block';"><i>Show Msg </i></h1>

<h1 onClick="javascript:document.getElementById('myDiv').style.display='none';"><i>Hide Msg</i></h1>

</body></html>

Page 7: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Can You Create This Alert Message?

Page 8: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

<html><body> <h1>Welcome to Div Control</h1><h1>Try this example to learn How</h1><h1>to position Div</h1><h1>Click on Show</h1><div id="myMsg"

style="top:200;left:100;position:absolute;border:groove;width:250px;height:120px;background-color:blue" >

<h3 align='center'>Alert Message</h3><div id="myDiv" style="top:22;left:-

4;position:absolute;border:groove;width:250px;height:100px;background-color:grey" >

<br /><b>&nbsp;&nbsp;Invalid Username or Password</b><p align='center'><form><input style='color:grey;background-color:blue'

type='button' onclick="javascript:document.getElementById('myMsg').style.display='none';" value="Close" /></form></p>

</div></div><h1

onClick="javascript:document.getElementById('myMsg').style.display='block';"><i>Show Div Msg </i></h1>

</body></html>

Page 9: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Arrays in JavaScript

Page 10: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Arrays in JavaScript

JavaScript treats arrays as objectsto create an array you must use the

keyword newvar a = new Array(); //empty arrayvar b = new Array(10); //array of size 10var c = new Array(2,5,34);

//array of size 3, values= 2,5,34

Page 11: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

var myArray=new Array(5); //size=5myArray[0] = "blue";myArray[1] = "red";myArray[4] = "purple";myArray[“red”]=“gold” which is

equivalent to myArray[1]=“gold”

Page 12: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

var musicArray = new Array(); //size=0musicArray[7] = "Close to the Edge";

//size=8musicArray[222] = "Yessongs";

//size=223

Page 13: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

var myArray1 = new Array("blue", "red", "purple", "lime", "yellow");

document.write(myArray1[0]);which would render the following output: blue

document.write(myArray1);which would render the following output, noting that JavaScript does not store theoptional space between Elements, but it does store the comma separator:blue,red,purple,lime,yellow

Page 14: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

for (var i=0; i < myArray1.length; i++) {document.write(myArray1[i] + "<BR />");}- Output:blueredpurplelimeyellow

Page 15: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

2-Dimensions array example<SCRIPT LANGUAGE="JavaScript1.2"> <!--a1 = new Array(2);for (var i=0; i<2; i++) {

//creates a new Array in each Element of Array a1a1[i] = new Array(5);for (var j=0; j<5; j++) {//assigns a value to each Element of the second dimension Array

a1[i][j] = i + ", " +j;//displays the values for the first dimension Array of Arrays

document.write(a1[i] + "&nbsp;&nbsp;&nbsp; First Dimension Array <BR>");

//displays the values for the second dimension Array Elementsdocument.write(a1[i][j] + "&nbsp;&nbsp;&nbsp; Second

Dimension Array Element <BR><BR>")}

}--></SCRIPT>

Page 16: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Arrays methods concat() Combines two Arrays and returns a new Array that's "one

level deep". join() Takes all Elements of an Array and converts them into one

String where each Element is separated by a comma or, optionally, your own separator.

pop() Removes and returns the last Element of an Array, changing its length.

push() Adds Element(s) to the end of an Array, returns the new length of the Array.

reverse() Reverses the physical order of the Elements in an Array. shift() Extracts the first Element of an Array and returns that Element. slice() Extracts a selectable portion of an Array and returns a new

Array. splice() Optionally adds, removes, or adds and removes Elements

from an Array. sort() Sorts the Elements of an Array lexicographically or by your

Function. toString() Returns a String that represents the calling Array Object or

Element. unshift() Adds one or more Elements before the first Element of an

Array. It returns nothing.

Page 17: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

<HTML><HEAD><SCRIPT LANGUAGE="JavaScript1.2"> <!--

a1 = new Array("blue", "red", "purple", "lime", "yellow");a2 = ["green", "gray", "black", "white", "olive"];

//---Note that a2 is an Array created with literal notation.--></SCRIPT></HEAD><BODY><!-- ************************************************ --><SCRIPT LANGUAGE="JavaScript"> <!--var str = "";str += '<P>Array a1 has these Elements: <B>' + a1 + '</B></P>';str += 'Array a2 has these Elements: <B>' + a2 + '</B><BR>';str += '<P>Array a1 concat a2: <B>' + a1.concat(a2) + '</B></P>';

Page 18: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

str += '<P>Array a1 with the Join Method: <B>' + a1.join(', ') + '</B></P>';str += 'Array a2 with the Join Method: <B>' + a2.join(', ') + '</B><BR><BR>';str += '<P>Array a1 Lexicographically Sorted is: <B>' + a1.sort() + '</B><BR>';str += 'Array a1 Lex. Sorted and Joined is: <B>' + a1.join(', ') +

'</B><BR><BR>';str += 'Array a1 Sorted and Reversed is: <B>' + a1.reverse() + '</B><BR>';str += 'Array a1 Sorted, Reversed and Joined is: <B>' + a1.join(', ') +

'</B></P>';str += 'Array a2 with the Push Method: <B>' + a2.push('cyan', 'maroon') +

'</B><BR>';str += 'Array a2 after the Push Method: <B>' + a2 + '</B><BR><BR>';str += '<H3>-----Note that the Unshift Method ';str += 'returns the number of Elements in the Array</H3>';str += 'Array a2 with the Unshift Method: <B>' + a2.unshift('navy',"violet") +

'</B><BR>';str += 'Array a2 after the Unshift Method: <B>' + a2 + '</B><BR><BR>';str += 'Array a2 with the Pop Method: <B>' + a2.pop() + '</B><BR>';str += 'Array a2 after the Pop Method: <B>' + a2 + '</B><BR><BR>';str += 'Array a2 with the Shift Method: <B>' + a2.shift() + '</B><BR>';str += 'Array a2 after the Shift Method: <B>' + a2 + '</B><BR><BR>';

Page 19: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

str += 'Array a2 with the Slice Method: <B>' + a2.slice(2,5) + '</B><BR>';str += '<H3>-----Note that the Slice Method does not alter ';str += 'the Array but returns a new Array</H3>';str += 'Array a2 after the Slice Method: <B>' + a2 + '</B><BR><BR>';str += 'Array a2 with the Splice Method: <B>' + a2.splice(3,2, 'gold','darkblue') +

'</B><BR>';str += '<H3>-----Note that the colors gold and darkblue are ';str += 'added in place of black and white</H3>';str += 'Array a2 after the Splice Method: <B>' + a2 + '</B><BR><BR>';str += 'Array a2 with the Splice Method: <B>' + a2.splice(1,4) + '</B><BR>';str += '<H3>-----Note that since no new colors are specified, ';str += 'Elements are simply removed</H3>';str += 'Array a2 after the Splice Method: <B>' + a2 + '</B><BR><BR>';str += 'using toString method for a2 <B>'+ a2.toString() +'</B>';document.write(str);--></SCRIPT></BODY></HTML>

Page 20: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2
Page 21: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2
Page 22: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Random Number Generator Example

<html> <body> <script language="javascript"> <!-- no=Math.random()*10; //random() returns a random number between 0 and 1 document.write(Math.round(no)); --> </script> </body> </html>

Page 23: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Exercise: write a random number generator (between 0 and 100) scripts?

Note:The Math object's properties and

methods are described in www.w3schools.com

Page 24: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Array Sort Function

Assume we have an array named: a1 To Sort Alphabetically in ascending order:

a1.sort(); To Sort Alphabetically in descending order:

a1.sort(); a1.reverse();

To sort numerically in ascending order: a1.sort( function(a,b) { return a-b; } );

To sort numerically in descending order: a1.sort(function(a,b) { return b-a; } );

To sort in random order: a1.sort( function() { return 0.5-Math.random(); } );

Page 25: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Strings in JavaScript

Javascript treats strings as objects to create a string you must use the keyword

new after a String object has been created then

there is a plethora of methods that can be invoked from that object

var a = new String(“test”); Var a=“test”;

Page 26: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

myString = new String("DreamPlay");Equivalent to:myString[0] = "D";myString[1] = "r";myString[2] = "e"; myString[3] = "a";myString[4] = "m"; myString[5] = "P"; myString[6] = "l"; myString[7] = "a";myString[8] = "y“;

Page 27: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Some String properties and methodslengthconcat()

// s1.concat(s2) is equivalent to s1=s1+s2split(regexp or string)

//Splits the source string into an array of strings (tokens) where its string argument specifies the delimiter

Page 28: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

The Split Method

<SCRIPT LANGUAGE="JavaScript1.2"> var str = "The Characters 1 & 2 & E & 3"; var splitArray=new Array(); splitArray = str.split("&"); document.write("<B>" + splitArray + "<\/B><P>"); document.write(“the Length of the array is ” + splitArray.length +

“<BR>”); document.write(splitArray[0] + "<BR>"); document.write(splitArray[1] + "<BR>"); document.write(splitArray[2] + "<BR>"); document.write(splitArray[3] + "<BR>"); </SCRIPT>

Page 29: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Slide Show Example<html><script language="JavaScript"><!--var myPix = new Array("ball1.gif","ball2.gif","ball3.gif");var thisPic = 0;function doPrevious() { if (document.images && thisPic > 0) { thisPic--; document.myPicture.src=myPix[thisPic]; }}function doNext() { if (document.images && thisPic < myPix.length) { thisPic++; document.myPicture.src=myPix[thisPic]; }}--></script><body><p align="center"><img name="myPicture" src="ball1.gif" width="100" height="57"><br><a href="javascript:doPrevious()">Previous</a><a href="javascript:doNext()">Next</a></body></html>

Page 30: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2
Page 31: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

More examples

<html><body><A HREF="mypage.html"

onMouseOver="window.status='Hi there!'; return true;" onMouseOut="window.status=' '; return true;">Place your mouse here!</A>

</body></html>

Page 32: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Example 2<FORM>

<INPUT type=”button” value=”Go Back” name=”backbutton” onClick=”history.back()”>

</FORM>In the same way, you can take a user forward instead of backward. Just change the code. Use onClick=”history.forward()”

Now you can also take a user back or front not in a step of one, i.e. the last page, but you can take him 4 pages back or 5 pages forward directly. Use the following code for it.onClick=”history.go(-4)” This is used to tell the browser to take the user 4 pages back.onClick=”history.go(5)” This is used to tell the browser to take the user 5 pages front.

Page 33: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Example 3

<FORM name="guideform"> <SELECT name="guidelinks" onChange="window.location=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value"> <OPTION SELECTED value="samepage.html”>--Choose--<OPTION value="page1.html">Page 1 <OPTION value="page2.html">My Cool Page </SELECT> </FORM>

Page 34: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Other JavaScript Objects

Page 35: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

The Date-object

this object lets you work with time and date. Example: displays the actual time. var today= new Date() This creates a new Date-object called today. If you do

not specify a certain date and time when creating a new Date-object the actual date and time is used. This means after executing today= new Date() the new Date-object today represents the date and time of this specific moment.

Page 36: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

The Date-object offers some methods which can now be used with our object today. This is for example getHours(), setHours(), getMinutes(), setMinutes(), getMonth(), setMonth()

Please note that a Date-object does only represent a certain date and time. It is not like a clock which changes the time every second or millisecond automatically.

Page 37: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

In order to get another date and time we can use another constructor (this is the Date() method which is called through the new operator when constructing a new Date-object):

today= new Date(1997, 0, 1, 17, 35, 23) This will create a Date-object which

represents the first of january 1997 at 17:35 and 23 seconds. So you specify the date and time like this:

Date(year, month, day, hours, minutes, seconds)

Page 38: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Example

<script language="JavaScript"> <!-- var now= new Date(); document.write("Time: " + now.getHours() + ":" +

now.getMinutes() + "<br>"); document.write("Date: " + (now.getMonth() + 1) + "/" +

now.getDate() + "/" + (now.getYear())); --> </script>

Page 39: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Output

Time: 17:53

Date: 12/19/2008

Page 40: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Timer Functions

TOid = setTimeout(statement,milisecond_to_wait);

- will execute a statement once when the time has run out.

INid = setInterval(statement,interval_in_miliseconds);

- will execute the statement every interval miliseconds.

Both can be cancelled as follows:

clearTimeout(TOid);

clearInterval(INid).

Page 41: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Timer example

<html><body><script language="JavaScript"><!-- function timer() {setTimeout("i()", 3000);}function i(){f.size=parseInt(f.size)+1;timer();} --></script><form><input type="button" value="Timer" onClick="timer()"><font size="1" id="f">test</font></form></body></html>

Page 42: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Clock Example<html><head><script Language="JavaScript"><!-- var timeStr, dateStr;function clock() {now= new Date();// timehours= now.getHours();minutes= now.getMinutes();seconds= now.getSeconds();timeStr= "" + hours;timeStr+= ((minutes < 10) ? ":0" : ":") + minutes;timeStr+= ((seconds < 10) ? ":0" : ":") + seconds;document.clock.time.value = timeStr;// datedate= now.getDate();month= now.getMonth()+1;year= now.getYear();dateStr= "" + month;dateStr+= ((date < 10) ? "/0" : "/") + date;

Page 43: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

dateStr+= "/" + year;document.clock.date.value = dateStr;Timer= setTimeout("clock()",1000);}// --></script></head><body onLoad="clock()"><form name="clock">Time:<input type="text" name="time" size="8" value=""><br>Date:<input type="text" name="date" size="8" value=""></form></body></html>

Page 44: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Cookies

A cookie is a way to store and retrieve a small piece of persistent data across multiple browser sessions from the client-side of the connection. Persistent data means that the data is available after the user disconnects from the WWW for reuse in the next session, or multiple sessions, if they are prior to the expiration date of the cookie.

When they were first introduced, Cookies were typically used to store the user's name and password for sites that require them, as a courtesy to the user so that the information doesn't have to be resubmitted every time the user logs on to a site. There are lots of other uses that authors have created for them, such as storing user Preferences for text size and color, etc. At a site that is transacting commerce, they could be used to store the items that the user has chosen to purchase like the shopping cart metaphor you've probably seen.

Page 45: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Cookie Syntax

document.cookie = "cookieName=cookieValue

[; EXPIRES=GMTDateString]

[; PATH=pathName]

[; DOMAIN=domainName]

[; SECURE]"

Page 46: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Parameters Defined:

cookieName=cookieValue You assign a name for the Cookie with the cookieName parameter and a value for the Cookie with the cookieValue parameter. They can be any sequence of characters except a semicolon, comma, or any white space.

PATH=pathName An optional parameter that specifies the path name.

DOMAIN=domainName An optional parameter that specifies the domain name.

SECURE An optional parameter that if included specifies that the Cookie will only be sent over a secure server.

Page 47: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Continued

EXPIRES=GMTDateString Sets an expiration time and date for the Cookie. This is an optional parameter and if it's omitted, then the Cookie expires at the end of the current session. The format of the String that is specified for the GMTDateString Value is:

Weekday, DD-Mon-YY HH:MM:SS GMTwhere: Weekday The day of the week like Monday. DD A two-integer representation of the day of the month like 05 or 22. Mon A three-letter abbreviation for the name of the month. YY A two-integer representation for the last two numerals of the year

like 99. HH The hours in military time from 0 to 23. MM The minutes like 04 or 33 where the zero is required for less than

10. SS The seconds where the zero is required for less than 10.

Note that the comma, dashes, colons, and spaces are necessary parts of the syntax.

Page 48: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Creating a Cookie is very simple. Using and manipulating Cookie data is royally difficult. Here is a simple example of creating a Cookie:

document.cookie="myCookie1=Eat_A_Cookie”; If you were to write the cookie to screen like

this:document.write(document.cookie); It would produce the following output in the

browser:myCookie1=Eat_A_Cookie

Page 49: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Using Cookies in your Scripts requires some creative manipulation of the text contained in the Cookie String. For instance, if you assign more than one Value to document.cookie, then it will contain a single String that contains each of those Values so that each one is separated by a semicolon. One way to access one of those Cookie Values later on is to use the split(";") Method of the String Object, and use the semicolon Character as the separator Argument, which will return an Array of Strings. Then, access individual Array Elements as needed, which is demonstrated in the following example.

Page 50: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

<HTML><HEAD><SCRIPT LANGUAGE="JavaScript1.2"><!--document.cookie="myCookie1=Eat_A_Cookie";document.cookie="myCookie2=Eat_Another_Cookie";document.cookie="myCookie3=Throw_A_Cookie";cookieString = document.cookie;cookieArray = cookieString.split(";");document.write(document.cookie + "<P>");document.write(cookieArray[0] + "<BR>");document.write(cookieArray[1] + "<BR>");document.write(cookieArray[2] + "<BR>");--></SCRIPT></HEAD><BODY>Make sure that your browser can accept Cookies or this won't work.</BODY></HTML>

Page 51: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

The Output

myCookie1=Eat_A_Cookie; myCookie2=Eat_Another_Cookie; myCookie3=Throw_A_Cookie

myCookie1=Eat_A_Cookie

myCookie2=Eat_Another_Cookie

myCookie3=Throw_A_Cookie

Page 52: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Another Example<HTML><BODY><H2>This Cookie has an Expiration Date.</H2><FORM NAME="form1">First and Last Name. <BR><INPUT TYPE='text' NAME='t1' SIZE=70> <BR><BR>The results are displayed in the Textarea. <BR>The testCookie is first and shows escaped characters. <BR>The cookie Value is next which is now unescaped. <BR><TEXTAREA NAME="ta1" ROWS=7 COLS=70></TEXTAREA>

<BR><BR><INPUT TYPE='button' VALUE='Update the Cookie named

testCookie' onClick='updateCookie(document.form1.t1.value);'><INPUT TYPE='button' Value='Cookie Value'

onClick=‘processCookie()'></FORM>

Page 53: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

<SCRIPT LANGUAGE="JavaScript"><!--function updateCookie(cookieString1) {var now = new Date();var expDate = new Date();// Fill in your own time numbers here.// day hr min sec millisecmyTime = now.getTime() + (1 * 24 * 60 * 60 * 1000);//Add your month here.//Put 0 or delete + 2 if you don't want//that much time added.myMonth = now.getMonth() + 2;expDate.setTime(myTime);expDate.setMonth(myMonth);document.cookie = "testCookie="+cookieString1+";

EXPIRES="+expDate.toGMTString();Document.forms[0].ta1.value= “Name: testCookie and Value: “ +

cookieString1;}//this cookie will expire after 2 months and one day (24h)

Page 54: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

function processCookie(){var cookieStr = document.cookie;cookieArray1 = cookieStr.split("; ");for (i=0; i<cookieArray1.length; i++) {cookieArray2 = cookieArray1[i].split("=");var str1=cookieArray2[0];var str2=cookieArray2[1];if (str1=="testCookie”) {

alert ("Cookie name: "+str1 + "\nValue: "+str2);break;}

}}--></SCRIPT></BODY></HTML>

Page 55: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Preferred Background Colour example

<html><body onLoad="processCookie()"><form> <p>My Preferred Background Color:&nbsp; <select size="1"

name="color"> <option selected value="white">Default (White)</option> <option value="yellow">Yellow</option> <option value="red">Red</option> </select></p> <p><input type="button" value="Update My Preference"

name="update" onClick="updateCookie(document.forms[0].color.value)"></p>

</form>

Page 56: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

<SCRIPT LANGUAGE="JavaScript"><!--function updateCookie(cookieString1) {var now = new Date();var expDate = new Date();// Fill in your own time numbers here.// day hr min sec millisecmyTime = now.getTime() + (1 * 24 * 60 * 60 * 1000);//Add your month here.//Put 0 or delete + 2 if you don't want//that much time added.myMonth = now.getMonth() + 2;expDate.setTime(myTime);expDate.setMonth(myMonth);document.cookie = "colorCookie="+cookieString1+";

EXPIRES="+expDate.toGMTString();document.bgColor=cookieString1;}

Page 57: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

function processCookie() {var cookieString2 = document.cookie;cookieArray1 = cookieString2.split("; ");for (i=0; i<cookieArray1.length; i++) {cookieArray2 = cookieArray1[i].split("=");var str1=cookieArray2[0];var str2=cookieArray2[1];if (str1=="colorCookie“){

document.bgColor = str2; break;}

}}--></SCRIPT></BODY></HTML>

Page 58: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

JavaScript Regular Expression

Is a sequence of characters and symbols to define a pattern of text, which can be used to test the contents of any text string.

Examples:var myExp=/top/

Page 59: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

var found=myExp.test (“Stop at the=>big top);

var myExp=/\btop\b/

Var myExp=/\d{3}/

Page 60: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2
Page 61: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2
Page 62: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

var charexp = /./; var letterexp = /[a-z]/i

Note: To include a character in a pattern that could be interpreted as a metacharacter, use the escape symbol (\) in front of the character. For example, the regular expression /\d{3}\.\d{2} specifies a pattern of three digits, followed by a period, followed by two digits. We've used the escape symbol in front of the period (.) because we want to represent an actual period, not the metacharacter (.).

Page 63: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Ex: number is required to have three digits (0-999) and we don't want any other extraneous characters before or after:

var memberexp = /^\d{3}$/;Ex: we have the option of either a five-digit

or a nine-digit ZIP code.

var zipexp = /^\d{5}$|^\d{5}[\-\s]?\d{4}$/;

Page 64: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Ex: Validating a phone number is simpler, especially if we simplify the problem by first stripping off any extraneous characters. We'll get to reformatting strings in a minute. Here's the regular expression:var phonexp = /^\d{10}$/

Ex: Now we get a bit more complicated, since email can take many different forms. Here's the expression:var emailexp = /^[a-z][a-z_0-9\.]+@[a-z_0-9\.]+\.[a-z]{3}$/i

Page 65: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

To test strings against a pattern

Example:var myExp = /\btop/;var found = myExp.test("Stop at the=>big top");

Note: Test method returns true or false

Page 66: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Replace Method

retStr= str.replace(pattern, anyValue);

myStr=str.replace(/[^0-9]/,’’);

myStr=str.replace(/[^0-9]/g,’’);

Page 67: ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

Reading

Chapter 10 ArraysChapter 11ObjectsChapter 13 Events


Recommended