Unit-4
Unit-4
<HTML>
<HEAD>
<TITLE>IGNOU </TITLE>
<SCRIPT LANGUAGE = "JavaScriptn>
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
JavaScript code should be written between the <SCRIPT> and </SCRIPT> tags. The
value LANGUAGE = "JavaScript" indicates to the browser that Javascript code has
' been used in the HTML document. It is a good programming practice to include the
i
I
Javascript code within the <HEAD> and </HEAD> tags.
Now let us start with variables. Variables store and retrieve data, also known as
"values". A variable can refer to a value, which changes or is changed. Variables are
subsequent characters can also be digits (0-9). Because JavaScript is case sensitive,
letters include the characters "A" through "Z" (uppercase) and the characters "a"
k L
through "z" (lowercase). Typically, variable names are chosen to be meaningful and
related to the value they hold. For example, a good variable name for containing the
r total price of goods orders would be t o t a l q r i c e .
You can also declare a variable bv s i m ~ l vassirnine a value to the variable. But if vou 1
assign to the variable is on to the right side. Thus the variable "stmame" shown above
gets the value "Hello" assigned to it.
CONTROL STRUCTURES
JavaScript supports the usual control structures:
The conditionals if, if...else, and switch;
The iterations for, while, do ...while, break, and continue;
if( myvariable == 2 ) {
myvariable = 1;
) else {
myvariable = 0;
1
If the value of myvariable in Figure 4.1 is 2 then the first condition evaluates to true
and the value of myvariable is set to 1. If it is anything other than 2 then the else part
gets exeyuted.
lntrod uction to
Now let us see an example of a nested if statement in Figure 4.2.
if ( myT7ariable= 2 ) {
myvariable = 1;
myvariable = 3;
Switch Statement
If there exist multiple conditions, the switch statement is recommended. This is
because only one expression gets evaluated based on which control directly jumps to
the respective case.
As shown in Figure 4.3, depending on the value of "myvar", the statement of the
respective case gets executed. If a case is satisfied, the code beyond that case will also
be executed unless the break statement is used. :n the above example, if myVar is 1,
the code for case 'sample', case 'false' and 'default' will all be executed as well.
For Statement
A for loop repeats until a specified condition evaluates to false. The JavaScript f o r
loop is similar to the Java and C for loops. A for statement looks as follows:
for ([iniriul-expression]; [condition]; [incremenz-expi.ession]){
<HTML>
<HEAD>
<TITLE>IGNOU </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function howMany(select0bject) {
var numberSelected=O
for (var i=O; i < selectObject.options.1ength;i++) {
if (selectObject.options[i].selected==true)
numberSelected++
1
return numberselected
1
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="selectForm">
<P><B>Choose some music types, then click the button below:</B>
<BRxSELECT NAME="musicTypes" MULTIPLE>
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
<OPTION> Classical
<OPTION> Opera
</SELECT>
<P><INPUT TYPE=llbutton" VALUE="How many are selected?"
onClick="alert ('Number of options selected: ' +
howMany(document.se1ectForm.musicTypes))"~
</FORM>
</BODY>
</HTML>
While Statement
The while statement defines a loop that iterates as long as a condition remains true. In
the following example the control waits until the value of a text field becomes "go":
while (Document.Form 1.Text1.Value != "go") {Statentents )
In a while loop the condition is evaluated first before executing the statements.
For In Statement
This is a different type of loop, used to iterate through the properties of an object or
the elements of an array. For example consider the following statement that loops
through the properties of the Scores object, using the variable x to hold each property
in turn:
For (x in Scores) {Statements)
Introc1111:tiotl
to
w Break Statement .la\ script
The break statement is used for terminating the current Whilc or For loop and then
transferring program control to the statement just after the terminated loop. The
following function has a break statement that terminates the while loop when i
becomes equal to 3, and then returns the value 3 * x.
function lestBreak(x) (
var i = 0
while (i < 6) {
if (i -= 3)
break
i ++
w Continue Statement
A continue statement terminates execution of the block of statements in a while or for
loop and continues execution of the loop with the next iteration. In contrast to the
break statement, continue does not terminate the execution of the loop entirely.
The following example shows a While loop with a continue statement that executes
when the value of i becomes equal to three. Thus, t~ takes on the values one, three,
seven, and twelve.
if (i == 3) continue
n += i
4.5.1 Functions
Functions are the central working units of JavaScript. Almost all the scripting code
uses one or more functions to get the desired result. If you want your page to provide
certain a user-defined functionality, then functions are a convenient way of doing so.
Therefore it is important that you understand what a function is and how it works.
First let us understand the basic syntax of a function; then we look at how to call it.
After that you must know how to pass arguments and why you need to do this.
Scripting Languages Finally, you have to know how to return a value from a function. The following code
shows the implementation of a function.
function example(a,b)
{
number += a;
alert('You have chosen: ' + b);
1
The function made above can be called using the following syntax.
Example(1 ,'house1)
In fact, when you define the function Example, you create a new JavaScript command
that you can call from anywhere on the page. Whenever you call it, the JavaScript
code inside the curly brackets {) is executed.
So this script first generates an alert box, then calls the function and after the function
is finished it continues to execute the rest of the instructions in the calling code.
Arguments
You can pass arguments to a function. These are variables, either numbers or strings,
which are used inside the function. Of course the output of the function depends on
the arguments you give it.
In the following example we pass two arguments, the number 1 and the string 'house':
example(1 ,'house');
When these arguments arrive at the function, they are stored in two variables, a and b.
You have to declare these in the function header, as you can see below.
function example(a,b)
<HTML>
<HEAD>
<TITLE>IGNOU </TITLE>
<SCRIPT Language = "JavaScriptW>
function example(a, b)
{
var number;
number += a ;
alert('You have chosen: ' + b);
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="selectForm">
<P><B>Click the button below:</B>
<BR>
<P><INPUT TYPE="button" VALUE="Click" onClick="example(l ,'house')">
</FORM>
-7
Introduction to
</BODY> JataScript
It adds 1 to number and displays "You have chosen: house". Of course, if you call the
function like example (5,'palacet), then it adds 5 to number and displays "You have
chosen: palace". The output of the function depends on the arguments you give it.
Returning a value
One more thing a function can do is to return a value. Suppose we have the following
<HEAD>
<TITLE>IGNOU </TITLE>
<SCRIPT Language = "JavaScript">
function calculate(a,b,c)
d = (a+b) * c;
return d;
</SCRIPT>
It means that you have declared a variable x and are telling JavaScript to execute
calculate( ) with the arguments 4, 5 and 9 and to put the returned value (81) in x.
Then you declare a variable y and execute calculate( ) again. The first argument is
x/3, which means 8113 = 27, so y becomes 150.0f course you can also return strings
or even Boolean values (true or false). When using JavaScript in forms, you can write
a function that returns either true or false and thus tells the browser whether to submit
a form or not.
Calling a function from the same script is very simple. You just need to specify the
name of the function, as demonstrated in Figure 4.9.
<HTML>
<HEAD>
<TITLE>Calling deferred code from its own script</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
makeLine(30)
function makeLine(1ineWidth) {
document.write("<HR SIZE=" + linewidth + ">")
1
makeLme(l0)
/I ->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Introduction to
.fattaScript
4.5.3 Objects
A JavaScript object is an instance of datatype. Object is given a unique name and the
collectiori of properties of the corresponding object may be accessed using the dot
syntax. As a quick introduction to the concept of JavaScript objects, here is the code
that creates an instance of an object called myObj:
var myObj = new Object();
myObj.business = "Voice and Data Networking"; myObj.CE0 = "IGNOU";
myObj.ticker = "CSCO";
After having run that code (in a scope situation that allowed myObj to be accessed as
required), you could run this ...
document.write("My Object ticker symbol is " + myObj.ticker + "."); .
Document Object
The document object is a property of the window object. This object is the container
for all HTML HEAD and BODY objects associated within the HTML tags of an
HTML document
Description
This is depreciated
Closes an output stream that was used to create a
document object
Contextual It can be used to specify style of specific tags. The I
following example specified that text in blockquotes is to I
be blue:
document.contextual(document.tags.blockquote).color =
"blue";
Multiple styles may be specified in the contextual
method to set the value of text in a <H3>tag that is
!
underlined to the color blue, for example.
dacument.contextual(document.tags.H3,
document.tags.U).color= "blue";
Scripting Languages ElementFromPoint(x, y) Returns the object at point x, y in the HTML document.
Getselection
open([mimeType])
Predefined Objects
Let us consider some of the most frequently used predefined objects provided in
Math object
In most applications we need to perform calculations, whether it is accounting
software or scientific software. Programmers are often typecast as good
mathematicians. Every mathematician needs a calculator sometimes, or in the case of
JavaScript, the Math object. If we want to calculate "2.5 to the power of 8" or
"Sin0.9" in your script, then JavaScriptls virtual calculator is what you need. The
Math object contains a number of manipulating functions:
var x= sin(3.5)
var result=max(x,y)
After creating an instance of the Date object, you can access all the methods o f the
object from the "my-date" variable. If, for example, you want to return the date (from
1-31 ) of a Date object, you should write the following:
my-date.getDate( )
You can also write a date inside the parentheses of the Date( ) object. The following
line of code shows some o f the date formats available.
new Date("Month dd, yyyy hh:mm:ssM),new Date("Month dd, yyyy"), new
Date(~y,mm,dd,hh,mm,ss),new Date(yy,mm,dd), new Date(mil1iseconds)
Here is how you can create a Date object for each of the ways above:
Explanation
Returns a Date object
Returns thc date of a Date object (from 1-31)
Rcturns the day of a Date object (from 0-6. O=Sunday,
I =Monday, etc.)
(ictMonth( ) Returns the month of a Date objcct (from 0-1 1 . O=January,
I=February, etc.)
1
GetHours( ) Returns the hour of the Date object (from 0-23)
GetMinutes( ) Returns the minute of the Date object (from 0-59)
GetSeconds( ) Returns the second of the Date object (from 0-59)
Returns the current date, including date, month, and year. Note that the getMonth
method returns 0 in January, 1 in February etc. So add 1 to the getMonth method to
Scripting Languages display the correct date.
<HTML>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPTY
var d = new Date()
document.write("date = ")
document.write(d.getDate( ))
document.write(".")
document.write(d.getMonth() + 1)
document.write(".")
document.write(d.getFul1Y ear())
document.write("time = ")
document. write(d.getHours())
document.write(".")
document.write(d.getMinutes() + 1)
document.write(".")
document.write(d.getSeconds())
</SCRIPT>
Time
Returns the current time for the timezone in hours, minutes, and seconds as shown in
Figure 5.1 1. To return the time in GMT use getUTCHours, getUTCMinutes etc.
Array Object
An Array object is used to store a set of values in a single variable name. Each value
is an element of the array and has an associated index number. You can refer to a
particular element in the array by using the name of the array and the index number.
The index number starts at zero.
You create an instance of the Array object with the "new" keyword.
var family-names=new Array(5)
The expected number of elements goes inside the parentheses, in this case it is 5.
You assign data to each of the elements in the array like this:
family-names[O]="Sharma" family-names[l]="Singh" family-names[2]="Gi11"
family_names[3]="Kumar" family_names[4]="Khan"
The data can be retrieved from any element by using the index of the array element
Methods Explanation
Lcngth Returns the number of elements in an array. This property is assigned a value
when an array is created
reverse( ) Returns the array reversed
slice( ) Returns a specified part of the array
Sort( ) Returns a sorted array
Method Description
reload The reload method forces a reload of the windows current document, i.e.
the one contained in the Location.href
Replace The replace method replaces the current history entry with the specified
URL.After calling the replace method to change the history entry, you
cannot navigate back to the previous URL using the browser's Back button.
<HTML>
<HEAD>
<SCRIPT LANGUAGE=" JAVASCRIPT">
function fnOpenModal() {
window.showModalDialog("test.htm)
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME = IGNOU>
<INPUT TYPE="button" VALUE=l1PushMe" onclick="fnOpenModal()">
</BODY>
</HTML>
The following example will generate a simple alert box based on clicking either a link
or a form button.
<htrnl>
<title~Codeave.com(JavaScript:Alert Box)</title>
<body bgcolor="#ffffffl>
<!-- Example of a form button that will open an alert box -->
<form>
<input type="button" value="Open Alert Box"
onClick='alert("Place your message here ... In Click OK to continue.")'>
</form>
<P>
<!-- Example of a link that will open an alert box -->
<a href='javas~ript:onClick=alert('~Placeyour message here ... \nClick OK to
continue. ")'>
Open Alert Box</a>
Scripting Languages
4.6.3 Confirm Boxes
The JavaScript confirm alert box differs from a regular alert box in that it provldes
two choices to the user, OK and Cancel. Typically, you'll see confirmation boxes
utilized on links where the destination is outside the domaln of the page you are
currently on or to alert you of potentially objectionable material. The following
example will display a confirmation alert box when either a link or form button is
clicked. Once either OK or Cancel are selected an alert box will follow to d~splay
which was chosen.
<html>
<body ~~coIoF"#FFFFFF">
<title>CodeAve.com(JavaScript: Confirm Alert Box)</title>
<script language="JavaScriptW>
<!--
function confirm-entry()
{
input-box=confirm("Click OK or Cancel to Continue");
if (input-box==true)
{
N Output when OK is clicked
alert ("You clicked OK");
1
else
{
I/ Output when Cancel is clicked
alert ("You clicked cancel");
1
-->
</script>
Click <a href;"JavaScript:confirm-entry()">here</a>
<P>
<form onSubmit="confirm-entry()">
<input type="submitW>
</form>
</body>
<html>
The text entry field is similar to a form input type="textV.The 2 buttons are OK and
Cancel. The value returned is either the text entered or null.
4.7.1 Events
Events are actions that can be detected by JavaScript. An example would be the
onMouseOver event, which is detected when the user moves the mouse over an
object. Another event is the onLoad event, which is detected as soon as the page is
finished loading. Usually, events are used in combination with functions, so that the
function is called when the event happens. An example would be a function that
would animate a button. The function simply shifts two images. One image that
shows the button in an "up" position, and another image that shows the button in a
"dowr," position. If this function is called using an onMouseOver event, it will make
it look as if the button is pressed down when the mouse is moved over the image.
For example, you might have a popup asking the user to enter his name upon his first
arrivai to your page. The name is then stored in a cookie. Furthermore, when the
visitor leaves your page a cookie stores the current date. Next time the visitor arrives
at your page, it will have another popup saying something like: "Welcome Ajay, this
page has not been updated since your last visit 8 days ago".
Another common use of the onLoad and onunload events is in making annoying
pages that immediately open several other windows as soon as you enter the page.
</HEAD>
<BODY>
<FORM NAME = "myform" >
<input type="textn name="myTextUvalue="Give me focus" onFocus =
"changeVal()">
</BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
s l = new String(myform.myText.value)
function changeVal() {
s l = "I'm feeling focused"
document.myform.myText.value= s l .toUpperCase()
1
</SCRIPT>
</HTML>
onblur = script
The onBlur event handler executes the specified JavaScript code or function on the
occurrence of a blur event. This is when a window, frame or form element loses
focus. This can be caused by the user clicking outside of the current window, frame
or form element, by using the TAB key to cycle through the various elements on
screen, or by a call to the window.blur method.
<SCRIPT LANGUAGE="JAVASCRIPT">
function addcheck() (
alert("P1ease check your email details are correct before submitting")
OnError
The onError event handler executes the specified JavaScript code or function on the
occurrence of an error event; This happens when an image or document causes an
error during loading. A distinction must be made between a browser error, when the
user types in a non-existent URL, for example, and a JavaScript runtime or syntax
error. This event handler will only be triggered by a JavaScript error, not a browser
Apart from the onError handler triggering a JavaScript function, it can also be set to
onError="null", which suppresses the standard JavaScript error dialog boxes. To
suppress JavaScript error dialogs when calling a function using onError, the function
must return true (Example 2 below demonstrates this).
There are two things to bear in mind when using window.onerror. First, this only
applies to the window containing window.onerror, not any others, and secondly,
window.onerror must be spelt all lower-case and contained within <script> tags; it
cannot be defined in HTML (this obviously does not apply when using onError with
an image tag, as in example 1 below).
The first example suppresses the normal JavaScript error dialogs if a problem arises
when trying to load the specified image, while Example 2 does the same, but applied
to a window, by using a return value of true in the called function, and displays a
customized message instead.
4.8 FORMS
Each form in a document creates a form object. Since a document can contain more
than one form, Form objects are stored in an array called forms.
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScripU
function window-onload()
{
var numberFonns = document.forms.length;
var fonnlndex;
for (fonnlndex = 0; formhdex < numberForms; formIndex++)
{
alert(document.forms[formIndex].name);
1
I
</SCRIPT>
m A D >
<BODY LANGUAGE=JavaScript onLoad="window~onload()"~
<FORM NAME="form1">
<P>This is inside form 1</P>
</FORM>
<FORM NAME="form2">
<P>This is inside forrn2</P>
</FORM>
<FORM NAME="form3">
<P>This is inside form3c/P>
</FORM>
</BODY>
</HTML>
Within the body of the page we define three forms. Each form is given a name, and
contains a paragraph of text. Within the definition of the <BODY> tag, the
window-onload( ) function is connected to the window object's onLoad event
handler.
<BODY LANGUAGE=JavaScript onload="return
window-onload( )">
This means that when the page is loaded, our window-onload() function will be
called. The window-onload( ) function is defined in a script block in the HEAD of
the page. Within this function we loop through the forms[ ] array. Just like any other
JavaScript array, the forms[ ] array has a length property, which we can use to
determine how many times we need to loop. Actually, as we know how many forms
there are, we could just write the number in. However, here we are also
demonstrating the length property, since it is then easier to add to the array without
having to change the function. Generalizing your code like this is a good practice to
The function starts by getting the number of Form objects within the forms array and
stores it in the variable numberForms.
function window-onload( )
Next we define a variable, formlndex, to be used in our for loop. After this comes the
alert(document.forms[formIndex].name);
Remember that since the indices for airays start at zero, our loop needs to go from an
index of 0 to an index of numberFom - 1. We do this by initializing the formIndex
variable to zero, and setting the condition ofthe for loop to fonnIndex <
numberForms.
Within the for loop's code, we pass the index of the desired form (that is, formlndex)
to document.forms[ 1, which gives us the Form object at that array index in the forms
array. To access the Form object's name property, we put a dot at the end and the
name of the property, name.
Form Object
Form is a property of the document object. This corresponds to an HTML input form
constructed with the FORM tag. A form can be submitted by calling the JavaScript
submit method or clicking the form SUBMIT button. Some of the form properties are:
Action - This specifies the URL and CGI script file name the form is to be
submitted to. It allows reading or changing the ACTION attribute of the HTML
<HTML>
<HEAD,
<SCRIPT LANGUAGE = "javascript">
function check ()
{ if (document.myform.email.value== "") {
alert("p1ease enter your email-id");
return false; }
</SCRIPT>
</HEAD>
<BODY>
Enter your Email to subscribe : <p>
<FORM Name = "myform" Action = "mailto:subscribe@abc.com" Method = POST
Enctype = "multipart/form-data" onsubmit = "return check()" >
<Input type = "text" Name = "email">
<Input type = "submit" value = "submit">
</BODY>
</HTML>
The above code. is used for obtaining the user's email-id. In case the user clicks the
submit button without entering the email-id in the desired text field, he sees a
message box indicating that the email-id has not been entered.
114
Scripting Languages {
var y=F1 .elements~].options[i].value;
s=new String(y);
var a=s.indexOf(">");
var b=s.substring(a+ 1,a+3);
c=parseInt(b);
d=d+c;
1
1
1
p="Total cost of the selected items="+d;
m=m+"\n"+p;
F 1.elements[3].value=m;
function clr(F1)
{
F1 .elements[3].value=" ";
1
</SCRIPT>
</HEAD>
<BODY>
<h2><font color="blue"><center> Welcome to the World renowned online Fast Food
Center </font>
<font color="red"> Donald Duck ! </centerx/font></h2>
<Form name="foml " ACTION = "mailto:dlc@ignou.ac.in" METHOD = POST>
Select the Menu Items of your choice and then click on the Total Cost to find the bill
amount-
<BR><BR>
<Table >
<TR valign=top ><td>
Major dishes :<BR>
<select name=? 1" MULTIPLE onBlur="mainitem(this.form)">
coption value="Onion cheese capsicum Pizza->300" selected> Onton cheese
capsicum Pizza
<option value="Onion mushroom Pizza->200"> Onion mushroom Pizza
<option value="Chicken Tikka Pizza->460"> Chicken Tikka Pizza
<option value="Cheese Pizza->] 5 0 5 Cheese Pizza
</select>
<BR><BR><Ad>
<td> </td><td> </td>
<td>
Soups :<BR>
<select name="s2" MULTIPLE onBlur="mainitem(this. form)">
<option value="Tomato Soup->70"> Tomato Soup
<option value="Sweet corn Soup->8OU>Sweetcorn Soup
<option value="Sweet n Sour soup->9OU>Sweetn Sour soup
<option value="Mixed veg soup->5OU>Mixedveg soup
</select>
<BR><BR></td>
<td> </td><td> </td>
<td>
Miscellaneous :<BR>
<select name="s3" onBlur="mainitem(this.form)">
<option value=" ">'Desserts1
<option value="Milkshakes->359Milkshakes
Introduction to
coption value="Soft drinks->2OU>Softdrinks
JavaScript
coption value="Ice cream sodas->25">Softy
<BR><BR></td>
<td> </td><td> </td>
<TR valign=top><td>
The items selected form the Menu are :
<TEXTAREA Name="TA 1 " Rows=lO Cols=50>
</TEXTAREA><BR><BR></td>
<td> </td><td> </td>
<HR noshade>
<h2><font color="red"> Personal Details </center></font></h2>
Email :<BR>
<Input Type = "Text" Name = "txt-email" Onblur = "clk_email()">
<BR><BR:.<Ad>
<td> </td>.=td> </td>
. ., . . . . . . . -. . . . . . .. . .
- -
!)cs,;;l; the fo!luwlng x e b pagc i l l kuch d \\a! ti;dt >electing ally option inhodwtba to
f:o!n Iht. ra?,,:~hutton d~spla;qs!he app:on!la:e rcsu!! t : ~the Result box. Jovrfiript
4
Stop 3cfresh t
"Y
i Sear&
3 LA ;
F i \ o i l t e ~ History ,
>A.
Md:l
AdJrs:s r :iiooh\ur~t5\Examplsc h g 5 html
Actiox~:
r Double
r Sqi~are
Products t o Ordrr:
4.9 SUMMARY
In this unlt we have learned about the major features of JavaScript. Besides normal
programrnlng constructs, datatypes and variables, we have also discussed the most
commonly used objects. These are: Document, Math, Date, History, Location etc. The
Submit and Reset objects are used to submit the information to the server and reset
the informat~onentered, respectively. Finally, we discussed a very important object,
the Form object.
Scripting Languages
4.10 SOLUTIONS1 ANSWERS
Check Your Progress 1
<HTML>
<HEAD>
<TITLE> Date validations </TITLE>
<SCRIPT>
var monthNames = new Array(l2);
monthNames[O]=="January";
monthNames[ 1]= "February";
monthNames[2]= "March";
monthNames[3]= "April";
monthNames[4]= "May";
monthNames[5]= "June";
monthNames[6]= "July";
monthNames[7]= "August";
monthNames[8]= "September";
monthNames[9]= "October";
monthNames[lO]= "November";
monthNames[l 1]= "December";
<BODY>
<Hl>WELCOME!</HI>
<SCRIPT>
document.write(customDateString( new Date()))
</SCRIPT>
</BODY>
</HTML>
Introduction to
function checkData(co1umn-data)
Javr~Script
column-data.value = column_data.value.toUpperCase( )
</SCRIPT>
</HEAD>
<FORM>
<INPUT TYPE="textWNAME="collector" SIZE=lO
onChange="checkData(this)">
<INPUT TYPE="textWNAME="dummyNSIZE=I O>
</FORM>
</BODY>
</HTML>
<HTML>
<HEAD>
cTITLE>Password Validation</TITLE>
<SCRIPT language="JavaScriptU>
function checkout()
if (document.survey.elements[x].value== "")
if(userpassword[i] == user)
if(userpasswordlj] == password)
Scripting Languages
{
flag=l ;
break;
1
1
i+=2;
1
if(flag == 0)
{
alert("P1ease enter a valid user name and password")
return;
1
else
{
alert("We1come !!\nu+document.forms[O].Usemame.value);
1
return;
1
/I-->
</SCRIPT>
</HEAD>
<BODY>
<FORM ACTION="" method="POSTUNAME="suwey"
onSubmit="retum checkOut(this.form)">
<INPUT TYPE="TEXTWNAME="Usemame" SIZE=" 15" MAXLENGTH=" IS">
User Name
<BRxINPUT TYPE="PASSWORD" NAME="Pasword" SIZE=" 1S">Password
< B R x M P U T TYPE="SUBMITNVALUE="SubmitU><MPUTTYPE="RESETU
VALUE="Start Over">
</FORM>
</BODY>
</HTML>
<HTML,
<HEAD>
<TITLE>Displaying the Date and time in the Browser</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
hncjion begintform)
{
form-name = form;
time-out=window .setTimeout("display_date()"
,500)
}
function display-date()
{
form-name.date.value=new Date();
1000)
time~out=window.setTimeout("display~date()',
1
function display-clock()
{
document.write('<FONT COLOR=red SIZE=+ 1><FORM
NAME=time-form><CENTERXBR><BR>CurrentDate & Time :I)
document.write(' <INPUT NAME=date size= 19 Introduction-to
value=" "</FORM></FONT></CENTER>') JnvsScript
begin(document.time-form)
</SCRIPT>
</HTML>
function goodbye( )
<TITLE>FORMS</TITLE>
<!-- This code allows to access the Form objects Elements Array I/-->
<SCRIPT Language="JavaScript">
function Ver(form 1)
v=forml .elements.length;
if (form1 .elements[3].name=="Buttonl")
<BODY>
<FORM Name-"Survey Form 1">
FLRST FORM: <ixb>Survey Form 1 <ibx/i><BR><BR>
First Name : <Input Type=Text Name="Text 1" Value=""><BR><BR>
<Input Type="radioUName="Radial " Value=""> Fresher
<Input Type="radioWName="RadiolU Value="">
Experienced<BRxBR>
<Input Type="ButtonVName="Buttonl " Value="Clickl "
onClick="Ver(fonn)">
*om>
<HMTL>
<HEAD>
<TITLE>FORMS</TITLE>
<!-- This code checks the Checkbox when the button is clicked I/-->
<SCRIPT Language='JavaScriptf>
function Chk(fl)
fl .Check.checked=true;
alert(" The Checkbox just got checked ");
fl .Check.checked=false;
fl .Radio[O].checked=true; I n t r d u r tion to
fl .Radio[l].checked=false;
alert(" The Radio button just got checked ");
</SCRIPT>
if(form.elements[2].checked)
form.result.value = form.entry.value * 2;
<CENTER><BR>
<BiValue:</B>
(INPUT TYPE="text" NAME="entryH VALUE=O>
-=BR><BR>
<SPACER Size= 190>
<B>Action:<B><BR>
Scripting Languages
<SPACER Size = 225>
<INPUT TYPE="radioWNAME="actionlU VALUE="twice"
onClick="calculate(this.form);">Double<BR>
<SPACER Size = 225>
<INPUT TYPE="radio" NAME="actionl " VALUE="square"
onClick="calculate(this.form);">Square <BR><BR>
<B>Result:</B>
<INPUT TYPE=text NAME="result" onFocus = "this.blur();">
</CENTER>
</FORM>
</BODY>
</HTML>
4. (Case Study)
cHTb4l)
<HEAD><TITLE>Order Form</TITLE>
<SCRIPT>
/I function to calculate the total cost field
function Total()
{ var tot = 0;
tot += (240 * document.order.qty1 .value);
tot += (270 * document.order.qty2.value);
tot += (300 * document.order.qty3.value);
tot += (600 * document.order.qty4.value);
document.order.totalcost.value= tot; }
/I function to update cost when quantity is changed
function UpdateCost(number, unitcost)
{ costname = "cost" + number; qtyname = "qty" + number;
var q = document.order[qtyname].value;
document.order[costname].value =q * unitcost;
Total();
1