Java Script
Java Script
Chapter 4
JavaScript
4.1 Overview of JavaScript
What is JavaScript?
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser. It means
that a web page need not be a static HTML, but can include programs that interact with the user,
control the browser, and dynamically create HTML content. The JavaScript client-side
mechanism provides many advantages over traditional CGI server-side scripts. For example, you
might use JavaScript to check if the user has entered a valid e-mail address in a form field. The
JavaScript code is executed when the user submits the form, and only if all the entries are valid,
they would be submitted to the Web Server. JavaScript can be used to trap user-initiated events
such as button clicks, link navigation, and other actions that the user initiates explicitly or
implicitly.
Advantages of JavaScript
Less server interaction: You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors: They don't have to wait for a page reload to see if they
have forgotten to enter something.
Increased interactivity: You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
Richer interfaces: You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Compiled By Fasil 1
WKU/CCI/IS Fundamentals of Internet Programming I
Limitations of JavaScript
Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reasons.
JavaScript cannot be used for networking applications because there is no such support
available.
JavaScript doesn't have any multithreading or multiprocessor capabilities. Once again,
JavaScript is a lightweight, interpreted programming language that allows you to build
interactivity into otherwise static HTML pages.
One of major strengths of JavaScript is that it does not require expensive development tools. You
can start with a simple text editor such as Notepad. Since it is an interpreted language inside the
context of a web browser, you don't even need to buy a compiler.
To make our life simpler, various vendors have come up with very nice JavaScript editing tools.
Some of them are listed here:
Microsoft FrontPage: Microsoft has developed a popular HTML editor called FrontPage.
FrontPage also provides web developers with a number of JavaScript tools to assist in the
creation of interactive websites.
Macromedia Dreamweaver MX: Macromedia Dreamweaver MX is a very popular HTML
and JavaScript editor in the professional web development crowd. It provides several
handy prebuilt JavaScript components, integrates well with databases, and conforms to
new standards such as XHTML and XML.
Macromedia HomeSite 5: HomeSite 5 is a well-liked HTML and JavaScript editor from
Macromedia that can be used to manage personal websites effectively.
Others: SublimeText3, Notepad++, aptana ….
The ECMAScript Edition 5 standard will be the first update to be released in over four years.
JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard, and the difference between the
two is extremely minor. The specification for JavaScript 2.0 can be found on the following site:
http://www.ecmascript.org/ Today, Netscape's JavaScript and Microsoft's JScript conform to
the ECMAScript standard, although both the languages still support the features that are not a
part of the standard.
Compiled By Fasil 2
WKU/CCI/IS Fundamentals of Internet Programming I
<script>
Block code
</script>
JavaScript where to?
You can place any number of scripts in an HTML document. Scripts can be placed in the <body>,
or in the <head> section of an HTML page, or in both. Scripts can also be placed in external files.
External scripts are practical when the same code is used in many different web pages. JavaScript
files have the file extension .js. To use an external script, put the name of the script file in the src
(source) attribute of the <script> tag:
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
You can place an external script reference in <head> or <body> as you like. The script will behave
as if it was located exactly where the <script> tag is located.
JavaScript Programs
Compiled By Fasil 3
WKU/CCI/IS Fundamentals of Internet Programming I
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed. JavaScript keywords are reserved words. Reserved words cannot be used as names
for variables.
Some Examples of keywords: var, function, if, for, break, switch ……..
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Two types of comments
Single line comment: Any text between // and the end of a line, will be ignored by JavaScript
Multiline Comment: Any text between /* and */ will be ignored by JavaScript.
Declaring Variables
var x;
var y;
A variable declared without a value will have the value undefined.
You can also assign a value to the variable when you declare it:
var x = 5;
var y = 6;
var z = x + y;
From the example above, you can expect:
Compiled By Fasil 4
WKU/CCI/IS Fundamentals of Internet Programming I
JavaScript Identifier
The general rules for constructing names for variables (unique identifiers) are:
JavaScript Datatypes
o JavaScript Strings - A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
var s1=‘john’;
o JavaScript Numbers - JavaScript has only one type of numbers. Numbers can be written
with, or without decimals:
var x=23;
var x=23.00;
Extra-large or extra small numbers can be written with scientific (exponential) notation:
var y=15e5;
o JavaScript Array - JavaScript arrays are written with square brackets. Array items are
separated by commas:
var array1=[“IS”, “CS” , “SE”];
o JavaScript Object - JavaScript objects are written with curly braces. Object properties are
written as name:value pairs, separated by commas.
var person = {firstName:"John", lastName:"Doe", age:50};
o JavaScript Boolean - Booleans can only have two values: true or false.
var x = true;
var y = false;
Compiled By Fasil 5
WKU/CCI/IS Fundamentals of Internet Programming I
Symbol Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
++ Increment
-- Decrement
Assignment Operators
Comparison Operators
Operator Description
== Equal to
!= Not Equal to
=== Equal Value and Equal type
!== Not Equal value and type
< Less than
> Greater than
<= Less than or Equal
>= Greater than or Equal
Logical Operators
Compiled By Fasil 6
WKU/CCI/IS Fundamentals of Internet Programming I
The if keyword is used to execute a statement or block only if a condition is fulfilled. Its
form is: if (condition)
statement
Where condition is the expression that is being evaluated. If this condition is true,
statement is executed. If it is false, statement is ignored (not executed) and the program
continues right after this conditional structure.
Syntax
if (expression)
statements;
For example, the following code fragment prints x is 100 only if the value stored in the x
variable is indeed 100:
if (x == 100)
document.write( "x is 100");
If we want more than a single statement to be executed in case that the condition is true
we can specify a block using braces { }:
if (x == 100)
{
document.write("x is ");
document.write( x);
}
Compiled By Fasil 7
WKU/CCI/IS Fundamentals of Internet Programming I
<html>
<body>
<script type="text/javascript">
<!--
var age = prompy(“Enter your age”,18);
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
</body>
</html>
We can additionally specify what we want to happen if the condition is not fulfilled by using the
keyword else. Its form used in conjunction with if is:
if (condition)
statement1;
else
statement2;
For example:
if (x == 100)
document.write( "x is 100");
else
document.write("x is not 100");
prints on the document x is 100 if indeed x has a value of 100, but if it has not -and only if not- it
prints out x is not 100.
3. The if else if statement
The if + else structures can be concatenated with the intention of verifying a range of values. The
following example shows its use telling if the value currently stored in x is positive, negative or
none of them (i.e. zero):
Syntax
if (x > 0)
alert("x is positive");
else if (x < 0)
alert("x is negative");
else
alert("x is 0");
Compiled By Fasil 8
WKU/CCI/IS Fundamentals of Internet Programming I
Remember that in case that we want more than a single statement to be executed, we must group
them in a block by enclosing them in braces { }.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
var greeting;
var time = new Date().getHours();
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
}
</script>
</body>
</html>
Compiled By Fasil 9
WKU/CCI/IS Fundamentals of Internet Programming I
Compiled By Fasil 10
WKU/CCI/IS Fundamentals of Internet Programming I
Switch Statement
The if and if/else statements become quite confusing when nested too deeply, and
JavaScript offers an alternative.
switch (expression)
{
case valueOne: statement;
break;
case valueTwo: statement;
break;
....
case valueN: statement;
break;
default: statement;
}
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}
Compiled By Fasil 11
WKU/CCI/IS Fundamentals of Internet Programming I
The while statement (also called while loop) provides a way of repeating a statement or a
block as long as a condition holds / is true.
The general form of the while loop is:
while(expression)
statements;
First expression (called the loop condition) is evaluated. If the outcome is non zero then
statement (called the loop body) is executed and the whole process is repeated. Otherwise, the
loop is terminated.
Example
Try the following example to implement while loop.
<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10){
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Example 2:
The following script will request the user to insert age until the user inserts valid age(1-130).
<!doctype html>
<html>
<head>
<title>While loop Test</title>
</head>
<body>
<script>
var x=0;
while((x<1) || (x>130)){
x=prompt("enter your age");
Compiled By Fasil 12
WKU/CCI/IS Fundamentals of Internet Programming I
}
alert("Thanks");
</script>
</body>
</html>
The do statement (also called the do while loop) is similar to the while statement,
except that its body is executed first and then the loop condition is examined.
In do…while loop, we are sure that the body of the loop will be executed at least once.
Then the condition will be tested.
The general form is:
do
{
statement;
}
while(expression);
Compiled By Fasil 13
WKU/CCI/IS Fundamentals of Internet Programming I
Thus, first expression1 is evaluated and then each time the loop is executed,
expression2 is evaluated. If the outcome of expression2 is non zero then statements is
executed and expression3 is evaluated. Otherwise, the loop is terminated.
Compiled By Fasil 14
WKU/CCI/IS Fundamentals of Internet Programming I
Syntax
<script type="text/javascript">
</script>
Example
<html>
<head>
<script type="text/javascript">
var func = new Function("x", "y", "return x*y;");
function secondFunction(){
var result;
result = func(10,20);
document.write ( result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
o Self-invoking function
(function () {
var x = "Hello!!"; // I will invoke myself
})();
Compiled By Fasil 15
WKU/CCI/IS Fundamentals of Internet Programming I
o Function Hoisting
Earlier in this tutorial, you learned about "hoisting". Hoisting is JavaScript's default behavior
of moving declarations to the top of the current scope. Hoisting applies to variable
declarations and to function declarations. Because of this, JavaScript functions can be called
before they are declared:
myFunction(5);
function myFunction(y) {
return y * y;
}
We can pass different parameters while calling a function. These passed parameters can be
captured inside the function and any manipulation can be done over those parameters. A function
can take multiple parameters separated by comma.
</html>
Compiled By Fasil 16
WKU/CCI/IS Fundamentals of Internet Programming I
o Function Closure
The ability to treat functions as values, combined with the fact that local variables are “re-created”
every time a function is called, brings up an interesting question. What happens to local variables
when the function call that created them is no longer active? The following code shows an
example of this. It defines a function, wrapValue, which creates a local variable. It then returns a
function that accesses and returns this local variable.
functionwrapValue(n){
var l o c a l V a r i a b l e = n ;
r e t u r n f u n c t i o n () { r e t u r n l o c a l V a r i a b l e ; };
}
var wrap1 = w r a p V a l u e (1) ;
var wrap2 = w r a p V a l u e (2) ;
c o n s o l e . log ( wrap1 () ) ;
// ! 1
c o n s o l e . log ( wrap2 () ) ;
// ! 2
This is allowed and works as you’d hope—the variable can still be accessed. In fact, multiple
instances of the variable can be alive at the same time, which is another good illustration of the
concept that local variables really are re-created for every call—different calls can’t trample on
one another’s local variables. This feature—being able to reference a specific instance of local
variables in an enclosing function—is called closure. A function that “closes over” some local
variables is called a closure. This behavior not only frees you from having to worry about lifetimes
of variables but also allows for some creative use of function values. With a slight change, we can
turn the previous example into a way to create functions that multiply by an arbitrary amount.
function multiplier( factor) {
return function ( number ) {
return number * factor ;
};
}
var twice = multiplier(2) ;
console . log ( twice (5) ) ;
// ! 10
The explicit localVariable from the wrapValue example isn’t needed since a parameter is itself a
local variable. Thinking about programs like this takes some practice. A good mental model is to
think of the function keyword as “freezing” the code in its body and wrapping it into a package
(the function value). So when you read return function(...){...}, think of it as returning a handle to
a piece of computation, frozen for later use. In the example, multiplier returns a frozen chunk of
code that gets stored in the twice variable. The last line then calls the value in this variable, causing
the frozen code (return number * factor;) to be activated. It still has access to the factor variable
from the multiplier call that created it, and in addition it gets access to the argument passed when
unfreezing it, 5, through its number parameter.
A variable created without a var keyword will be treated as global variable even
though it is created inside a function.
Compiled By Fasil 17
WKU/CCI/IS Fundamentals of Internet Programming I
function sayHello() {
document.write ("Hello World")
}
</script>
</head>
<body>
<p> Click the following button and see result</p>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
o onsubmit event type: onsubmit is an event that occurs when you try to submit a form.
You can put your form validation against this event type.
Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the webserver. If validate() function returns true, the form
will be submitted, otherwise it will not submit the data.
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
Compiled By Fasil 18
WKU/CCI/IS Fundamentals of Internet Programming I
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>
Compiled By Fasil 19
WKU/CCI/IS Fundamentals of Internet Programming I
Document object: Each HTML document that gets loaded into a window becomes a
document object. The document contains the contents of the page.
Form object: Everything enclosed in the <form>...</form> tags sets the form object.
Form control elements: The form object contains all the elements defined for that object
such as text fields, buttons, radio buttons, and checkboxes.
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
In the DOM, all HTML elements are defined as objects. The programming interface is the
properties and methods of each object. HTML DOM methods are actions you can perform on
HTML Elements (like add or deleting an HTML element). HTML DOM properties are values of
HTML Elements that you can set or change (like changing the content of an HTML element).
The HTML DOM can be accessed with JavaScript (and with other programming languages).
The HTML DOM Document
The document object is your webpage. The document object is the owner of all other objects
in your web page. If you want to access objects in an HTML page, you always start with
Compiled By Fasil 20
WKU/CCI/IS Fundamentals of Internet Programming I
accessing the document object. Below are some examples of how you can use the document
object to access and manipulate HTML.
Method Description
Property Description
Compiled By Fasil 21
WKU/CCI/IS Fundamentals of Internet Programming I
Methods Description
<html>
<body>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
Compiled By Fasil 22
WKU/CCI/IS Fundamentals of Internet Programming I
document.getElementById(id).attribute=new value
This example changes the value of the src attribute of an <img> element:
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
Example explained:
Example
<html>
<body>
<script>
document.getElementById("p2").style.color = "blue";
</script>
Compiled By Fasil 23
WKU/CCI/IS Fundamentals of Internet Programming I
</body>
</html>
Method Description
Events are generated by the browser when "things happen" to HTML elements:
An element is clicked on
The page has loaded
Input fields are changed
Method Descriptoin
This example changes the style of the HTML element with id="id1", when the user
clicks a button:
Compiled By Fasil 24
WKU/CCI/IS Fundamentals of Internet Programming I
Example
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
o Event Attributes
Example:
<body onload="checkCookies()">
Compiled By Fasil 25
WKU/CCI/IS Fundamentals of Internet Programming I
Below is an example of how to use the onchange. The upperCase() function will be
called when a user changes the content of an input field.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
</script>
</head>
<body>
</body>
</html>
<html>
Compiled By Fasil 26
WKU/CCI/IS Fundamentals of Internet Programming I
<body>
style="background-
color:#D94A38;width:120px;height:20px;padding:40px;">
<script>
function mOver(obj) {
function mOut(obj) {
</script>
</body>
</html>
<html>
<body>
Compiled By Fasil 27
WKU/CCI/IS Fundamentals of Internet Programming I
style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>
<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
</script>
</body>
</html>
Most often, the purpose of data validation is to ensure correct input to a computer
application.
Compiled By Fasil 28
WKU/CCI/IS Fundamentals of Internet Programming I
Validation can be defined by many different methods, and deployed in many different
ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.
HTML Constraint validation
Attribute Description
disabled specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern specifies the value pattern of an input element
required Specifies that the input field requires an element
type Define the minimum value of an input element
Compiled By Fasil 29
WKU/CCI/IS Fundamentals of Internet Programming I
o Validity Properties
The validity property of an input element contains a number of properties related to the
validity of data:
Property Description
customError Set to true, if a custom validity message is set.
patternMismatch Set to true, if an element's value does not match its pattern
attribute.
rangeOverflow Set to true, if an element's value is greater than its max
attribute.
rangeUnderflow Set to true, if an element's value is less than its min attribute.
stepMismatch Set to true, if an element's value is invalid per its step attribute.
tooLong Set to true, if an element's value exceeds its maxLength
attribute.
typeMismatch Set to true, if an element's value is invalid per its type attribute.
valueMissing Set to true, if an element (with a required attribute) has no
value.
valid Set to true, if an element's value is valid.
Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol.
But for a commercial website, it is required to maintain session information among different
pages. For example, one user registration ends after completing many pages. But how to maintain
users' session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for better visitor experience
or site statistics.
Your server sends some data to the visitor's browser in the form of a cookie. The browser may
accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now,
when the visitor arrives at another page on your site, the browser sends the same cookie to the
server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields:
o Expires: The date the cookie will expire. If this is blank, the cookie will expire when the
visitor quits the browser.
Compiled By Fasil 30
WKU/CCI/IS Fundamentals of Internet Programming I
o Path: The path to the directory or web page that set the cookie. This may be blank if you
want to retrieve the cookie from any directory or page.
o Secure: If this field contains the word "secure", then the cookie may only be retrieved
with a secure server. If this field is blank, no such restriction exists.
o Name=Value: Cookies are set and retrieved in the form of key-value pairs.
JavaScript can also manipulate cookies using the cookie property of the Document object.
JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
document.cookie = "key1=value1;key2=value2;expires=date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then
the cookie will expire on a given date or time and thereafter, the cookies' value will not be
accessible.
Note: Cookie values may not include semicolons, commas, or whitespace. For this reason, you
may want to use the JavaScript escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the corresponding unescape() function when you
read the cookie value.
Example
Try the following. It sets a customer name in an input cookie.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( document.myform.customer.value == "" ){
alert ("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
Compiled By Fasil 31
WKU/CCI/IS Fundamentals of Internet Programming I
</form>
</body>
</html>
Now your machine has a cookie called name. You can set multiple cookies using multiple
key=value pairs separated by comma.
Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the document.cookie
object is the cookie. So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons, where
name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows:
Example
Try the following example to get all the cookies.
<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Note: Here length is a method of Array class which returns the length of an array. We will
discuss Arrays in a separate chapter. By that time, please try to digest it.
Note: There may be some other cookies already set on your machine. The above code will
display all the cookies set on your machine.
Compiled By Fasil 32
WKU/CCI/IS Fundamentals of Internet Programming I
You can extend the life of a cookie beyond the current browser session by setting an expiration
date and saving the expiry date within the cookie. This can be done by setting the ‘expires’
attribute to a date and time.
Example
Try the following example. It illustrates how to extend the expiry date of a cookie by 1
Month.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
Deleting Cookies
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie
return nothing. To do this, you just need to set the expiry date to a time in the past.
Example
Try the following example. It illustrates how to delete a cookie by setting its expiry date to
one month behind the current date.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
Compiled By Fasil 33
WKU/CCI/IS Fundamentals of Internet Programming I
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
Compiled By Fasil 34