You are on page 1of 40

What is a scripting language?

A scripting language is a simple programming language designed to enable computer users to write useful programs easily. What is JavaScript? JavaScript is one of a new breed of Web languages called client side scripting language. These are simple languages that can be used to add extra features to Web page. You can program in JavaScript easily, no development tools or compilers are required. You can use the same editor you used to create HTML documents to create JavaScript, and it executes directly on the browser (i.e. Microsoft Internet Explorer). JavaScript was originally developed by Netscape Corporation for use in its browser, Netscape Navigator. It includes a convenient syntax easily accessed by the browser. The file of JavaScript should be saved with the extension .html for internal javascript and with .js for external javascript. It is started with <script language=javascript> and ends with </script> Uses of JavaScript The most important uses for JavaScript are: Validating Forms Making Pages Interactive by Including Dynamic Information. Note: - JavaScript keywords, function and object names, and variable names are case-sensitive. Be sure you use the correct combination of upper and lowercase when entering JavaScript statements. Note: - the semicolon at the end of the statement indicates the end of a statement (which is optional) . Variable Variable is a location or memory which is used for the storage of data temporarily (i.e. RAM) Variable name can begin with an uppercase letter (A Z), lowercase (a-z), dollar sign character ( $ ). var keyword is used to declare variables. (which is optional) Example: <script language="javascript"> var a,A; a=5; A=7; document.write(a+A); </script> Escape characters in JavaScript \n new line character. \t Tab character. Note:- Escape characters is only used with <pre> command.

Example of escape character: <script language="javascript"> var n="navin"; var a="patan"; var p=6564466; var g="male"; document.write("<h3 align='center'>esc</h3><hr>"); document.write("<pre>Name\t:\t",n); document.write("\nAddress\t:\t",a); document.write("\nphone\t:\t",p); document.write("\ngender\t:\t",g); </script>

Comments Comments are used in programming to store notes about something like logic, reminder etc. Comments are also used for debugging (finding and solving errors in the program) Statements or commands inside or within scope of comments are not executed or interpreted by the browser. Types of comments 1) Single line comment // 2) Multiple line comment /**/
Example: <script> var a=10; var b=5; var c; //to solve the result of division /* c=a/b; document.write(c);*/ document.write(a*b); </script>

DATA TYPE Data type means type of data stored by the variables. We dont have to declare data type while declaring variables. Javascript automatically change data type after assigning the value to a variable. There are different types like: number, string, Boolean, null etc. 1. Number:- It converts the number into integer or float data type. Example: - var a=5; 2. String: - It is a text and used within the double quotes ( ) Example:- var naam=Ram;

3. Boolean: - Boolean means true or false. Example: - var a=2; var b=3; var c=a>b; 4. Null: - The null value indicates that a variable is uninitialized. It is the assigning value to a variable as blank or zero.
Example <script language="javascript"> var ADD=30,add=40,ADd=50 document.wrte(ADD+"<br>"); document.write(add+"<br>"); document.write(ADd+"<br>"); </script>

Type Casting/ Data Type Conversion Type casting is the process of converting the value of variable from one data type to another.

This is also known as data type conversion. JavaScript provides 3 main functions for type casting: 1) eval() 2) parseInt() 3) parseFloat() 1. eval():-This function converts a compatible string to a numerical value. Example: <script> var a="25"; var b="50"; var c=a+b; document.write("<pre>") document.write("\n value of a\t:\t"+a)

document.write("\n value of b\t:\t"+b) document.write("\n sum of a and b\t:\t"+c) var d=eval(a)+eval(b); document.write("<h1 align=center>Using eval function</h1>"); document.write("\n sum of a and b\t:\t"+d+"</pre>"); </script> 2) parseInt() It extracts the first integer part from any given string that begins with an integer. If the string does not begin with an integer then this function returns NaN.

For example: num=parseInt(123.5string ); //it returns 123. Num=parseInt(xyz123); /*it returns NaN because the string xyz123 does not begin with an integer.*/ 3) parseFloat() This Function is same as parseInt(). The only difference is that it extracts the first floatingpoint number from the given string. For example parseFloat(1.23xyz) returns 1.23 and parseFloat (xyz1.23) returns NaN.

<script language='javascript'> document.write("<h2 align='center'>parseFloat function</h2>"); document.write("<hr color='red'>"); var a='s45'; var b='35.7'; var c='46.5sa'; var d='37.6e'; document.write("<pre><h3>value of a\t",a); document.write("\nvalue of b\t",b); document.write("\nvalue of c\t",c); document.write("\nvalue of d\t",d); document.write("<center> using parseFloat function</center>"); a=parseFloat(a); b=parseFloat(b); c=parseFloat(c); d=parseFloat(d); document.write("\nvalue of a\t",a); document.write("\nvalue of b\t",b); document.write("\nvalue of c\t",c); document.write("\nvalue of d\t",d); </script>

Input/output Function 1) prompt(" "," ") :-It is used to input any value to the variables. Example: var a=prompt("Enter any value"," ") document.write(a); 2) alert(" ") :It displays the value as alert message. Example: alert("welcome to my page"); Example of (alert and prompt): <script> var name,add,phone,email; alert("Welcome To My Page") name=prompt("Enter Your Name","") add=prompt("Enter Your Address","") phone=prompt("Enter Your Phone","") email=prompt("Enter Your Email","") document.write("<pre>") document.write("<h1 align=center>Example Of Prompt And Alert <hr color= skyblue> </h1>"); document.write("<h2>Your Name is\t\t:\t",Name); document.write("\nYour Address Is\t:\t",Add); document.write("\nYour Phone Is\t\t:\t",Phone); document.write("\nYour E-mail Is\t:\t",Email); document.bgColor="pink"; document.fgColor="white"; </script> Operator An operator is a symbol that performs a particular task by acting on operand. Operand:-it is the value in which the operator acts. Expression:-combination of an operator and its operand is known as expression. E.g.:- 2 + 3 = 5 where 2 and 3 are operands, + is operator 2 + 3 is expression. Types of Operator Unary operator:-This operator which requires only a single operand. There are two types of unary operator: Increment Operator (++):-Increases the value by 1. Decrement Operator (--):-Decrease the value by 1.

Binary Operator:-Binary operator is an operator, which requires two operands. For example: A*B Arithmetic Operators:-Arithmetic Operators are symbols, which are used to calculate the arithmetic calculation. There are four basic types of arithmetic operators which are given in table format: Symbols Meaning + It is used to add the numbers and concate string.

/ *

It is used to subtract the numbers. It is used to calculate the division. It is used to calculate the product.

Comparison Operators:-Operators used for comparing two or more values on the basis of a certain condition are known as comparison operators. The Comparison operators compare the operand on the left with the operand on the right and evaluate to either true or false'. The operands can be numerical values. For example: Is 2 greater than 9 ?(false) Is 9 greater than 2 ?(true) Following are Comparison operators: Less than(<) Less than or Equal to(<=) Greater than(>) Greater than or Equal to(>=) Equal to(==) Not equal to(!=)

Assignment Operator a) =(Equals) Assigns values at right to variable at left. Example v1=5; //The value of v1 is 5. V2=v1; //new value of v1 is assigned to V2. b) += Adds the value at right with value in the variable at left and assigns back the sum value to the variable at left. Example v1=5; v1+=2; //This is equal to v1=v1+2 c) - = Subtracts the value at right from value in the variable at the left and assign back the resulting value to the variable at left. Example v1=5; v1-=2; //This is equal to v1=v1-2 d) *= Multiplies the value at the right with value in the variable at the left and assigns back the resulting value to the variable at left. e.g. v1=5; v1*=2; //This is equal to v1=v1*2 e) /= Divides the value in variable at the left by value at right and assign back the resulting value to the variable at left. e.g. v1=5; v1/=2; //This is equal to v1=v1/2 f) %= Divides the value in variable at left by value at right and assigns back the modulus value to the variable at left. e.g. v1=5; v1%=2; // This is equal to v1=v1%2 Logical operators

Logical operators are similar to comparison operators, the only difference is that logical operators take Boolean values (True or False) as operands and return a Boolean value. Following are logical operators: AND :&& OR :|| NOT :! AND Operator:-This operator checks more than one condition and if all the conditions are true then only it returns true; returns false if any of the condition is false. The symbol used for AND operator is &&. OR Operator: This operator also checks more than one conditions. It returns true even if a single condition is true but return false when all conditions are false. The symbol used for OR operator is ||. NOT Operator:-This operator return true when the condition is false and return false when the condition is true. The Symbol used for NOT operator is ! . The NOT operator uses a single operand. NOT (Quantity<8) Table represents the result of this condition. Quantity 3 10 2 9 Quantity<8 True False True False NOT(Qnt<8) False True False true

Looping Statement Looping is the process of repeating statements for certain number of times or until some condition is true to stop the loop. It is a structure of statement used to execute a statement for many times. 1) for :It is a loop which checks the condition and prints the value. Syntax :for (initialization; loop-condition; increment/decrement) { statement; } 2) while :It is a loop which checks the condition first and prints the value after . Syntax :initialization; while (loop-condition) { statement; increment/decrement; } 3)do while :-It is a loop which prints the value first and after checks the condition. Syntax: initialization; do { statement; increment/decrement; } while (loop-condition) Examples: <script language="javascript"> //Using for loop for (a=1;a<=10;a+=2) //a=1+2 {

document.write("Congratulation!! for the SLC passed students ^_^<br>"); } </script> Example 2: <script language="javascript"> /*Using while loop generating natural numbers less than 100 in ascending order*/ x=1; while (x<=100) { document.write(x,"<br>"); x++; } </script> Example 3: <script language="javascript"> /*Using do while loop generating message*/ x=1; do { document.write("Concentrate!! on your studies<br>"); x++; } while (x>=5) </script> Example: <script language="javascript"> var i=1; document.write("<h1 align='center'>Do While Loop</h1><hr color='red'>"); do { document.write("<pre>Do while loop\t"+i+"\n"); i++; } while(i<10) document.bgColor="lightyellow" </script>

Conditional Statements/ Control structures 1) if Conditon: - This Control statement is basically used to apply some condition to the normal statement such that if the condition is true the statement will be executed other wise will be ignored. Syntax : if (condition) { statement; } Example:<script> var a="kathmandu" if (a=="kathmandu") { alert("right answer") } </script> (ii) if else: -This Control selection statement is used to evaluate the condition that have two actions, true case will result true and if the condition is false it returns false. Syntax : if (condition) { statement;

} else { statement; } Example:<script> var a="kathmandu" if(a=="kathmandu") {alert("right answer")} else {alert("wrong answer")} </script> (iii) ifelse if .... else :This selection statement is used to implement the multiple conditions with their respective actions. Syntax: if (condition1) { statement; } else if (condition2) { statement; } else if (condition3) { statement; } else { statement; } Example:<script> var ms="m"; if(ms=="m") {document.write("mon")} else if(ms=="t") {document.write("tue")} else if(ms=="w") {document.write("wed")} else if(ms=="th") {document.write("thu")} else {document.write("Others")} </script> Program to display the greatest no. using if else if else statement <script> document.write("<h1>Program to determine the greatest number</h1>"); var n1=prompt("Enter the first number","n1"); var n2=prompt("Enter the second number","n2"); var n3=prompt("Enter the third number","n3"); if (n1>n2 && n1>n3) { document.write("The greatest number is " +n1+ " among "+ n1+ ", " +n2+ "and "+ n3); } else if (n2>n1 && n2>n3) { document.write("The greatest number is " ,n2, " among ", n1, ", " ,n2, "and ", n3); } else { document.write("The greatest number is " ,n3, " among ", n1, ", " ,n2, "and ", n3); }

</script> Switch-case statement:-The switch-case statement is used when a variable is to be successively compared against different values. Example:<script> var Day=prompt(Enter day of a week:Sun|Mon||Sat, ); switch(Day) { case "Sun": { document.write("sunday"); break; } case "Mon": { document.write("monday"); break; } case "Tue": { document.write("tuesday"); break; } case "Wed": { document.write("Wednesday"); break; } case "Thu": { document.write("thursday"); break; } case "Fri": { document.write("friday"); break; } case "Sat": { document.write("Saturday"); break; } default: { document.write("not a day"); } } </script> <script> var Day=prompt("Enter day of a week","Sun|Mon|Tue...") switch (Day) { case "Sun": { document.write("No pain!No gain"); break; } default: { document.write("Bye! Bye!!"); } } </script>

ARRAY Array is static data structure, where values are stored with same array name but different index numbers. Declaring ARRAY Syntax: arrayName=new Array(no. of cells) OR arrayName=new Array(item1,item2,item3,..,itemn) Note: The index number of first element of array is Zero [0] The index number of last element of array is n-1. Where n=total number of element in the array. Example:<script language="javascript"> student=new Array ("dibya","sudin","Rujin","Bishnu","Jems"); phone=new Array (5539522,5539340,5550135,5550135,5550134); document.write(student,"<br>"); document.write(phone); </script>

<script language=''javascript''> months=new Array(12) months[0]=''Jan''; months[1]=''Feb''; months[2]=''March''; months[3]=''April''; months[4]= ''May''; months[5]=''June''; months[6]=''July''; months[7]=''Aug''; months[8]=''Sep''; months[9]=''Oct''; months[10]=''Nov''; months[11]=''Dec''; document.write(months); document.write("<br>", months[1]); document.write("<br>", months[10]); document.write("<br>Length of array",months.length); document.write("<br>Last index of array",months.length-1); document.write("<br>Reverse array",months.reverse()); </script>

FUNCTION Function is a small module of a program that works like a separate program. Functions are basically used to group the related statement together to make the programming easier to program. To create any function, we need first declare and at last we have to call this function otherwise it doesnt work. Placing most frequently used statements inside a separate function: a. allows reusability of code b. c. Syntax: helps to avoid repetition of code reduces redundancy

function func_name() { Statements; } Example using function <script> var a=eval(prompt("Enter a no.","N1")); var b=eval(prompt("Enter next no.","N2")); function SUM() { alert (a+b); } function DIFF() { alert (a-b); } </script> <body> <input type="button" value="Add" onclick="SUM()"> <input type="button" value="Subtract" onclick="DIFF()"> </body> Example 2:<html> <head> <script> function myfunc() { a=120; b=80; alert(a+b); } function gray() { document.bgColor="gray"} function yellow() {document.bgColor="yellow"} function green() {document.bgColor="green"} function black() {document.bgColor="black"} function blue() {document.bgColor="blue"} </script> </head> <body> <input type=button value=calculate onclick="myfunc()"> <input type=button value=gray onclick="gray()"> <input type=button value=yellow onclick="yellow()"> <input type=button value=green onclick="green()"> <input type=button value=black onclick="black()"> <input type=button value=blue onclick="blue()"> </body> </html>

String Object String is also an object in JavaScript but we can directly create this object by assigning string value to any variables. new keyword is not needed to declare string. E.g. var a=Ram String Object Function 1) toUpperCase() :- It displays or gives all the characters of a string to uppercase. E.gvar a=kathmandu document.write(a.toUpperCase()) 2) toLowerCase() :- it displays all the characters of a string to lowercase. E.g. alert(a.toLowerCase())

3) length :It displays or count the number of characters in the strings. e.g. alert(a.length) 4) substring() :It is used to extract a string from another string. e.g. var a=kathmandu alert(a.substring(4,7)) here 4 is starting and 7 is ending position. 5) charAt() :- It shows the character of the string at the specified position. e.g. alert(a.charAt(4)) here 4 is the position of string. 6) indexOf() :it is used to search something inside a string and returns its position in number. It displays (-1) if it doesnt find any value. eg alert(a.indexOf(man))

Declaring Date Object Syntax: dateName=new Date() Date properties 1. getHours() 2. getMinutes() 3. getSeconds() Example <script language="javascript"> mydate=new Date() a=mydate.getHours() b=mydate.getMinutes() c=mydate.getSeconds() document.write

(a, " hrs", b, " mins" , c, " secs"); </script>


Example 2 <html> <head> <title>Greetings</title> <script language="javascript"> function greetings() { mydate=new Date() var a=mydate.getHours() if (a<=6) alert ("Very Good Morning!!") else if (a>6 && a<=12) alert ("Good Morning!!") else if (a>12 && a<=17) alert ("Good Afternoon!!") else alert("Good Evening!!") } </script> </head> <body onload=''greetings()''> <h2 align="center">Greeting Message according to time</h2> </body> </html> EVENTS Events :- Event represents a situation or generally the action performed by user or occurred due to your action which can be trapped by the some facts about event: Mouse Events =>onMouseOver =>onMouseOut =>onClick =>onMouseUp =>onMouseDown =>onDblClick =>onMouseMove Other Events (Body Object) onClick onBlur onMouseDown onMouseUp onKeyPress onMove onResize onLoad onUnload onFocus #onMouseOver :- When user place the mouse over an object. # onMouseOut :- When user place the mouse out of an object. # onClick :- When user presses the mouse key and release it . # onMouseDown :-When user press the mouse button (until the release the button) # onMouseUp :- When user release the mouse button (After mouse key is pressed) # onMouseMove :- When user moves the mouse. # onDblClick :- When user double click mouse button. # onKeyPress:- When user presses the key and release it. # onKeyDown :- When user press the key. #onKeyUp:- When user release the key (After pressing it) #onChange :- When content of text box is changed. #onSelect :- When the content of text box is selected. Example using Events <script>

a=prompt("Enter a string", "text") function a1() { alert(a.toUpperCase()) } function a2() { alert(a.toLowerCase()) } function a3() { alert(a.length) } function a4() { alert(a.length-1) } function a5() { x=eval(prompt("Enter an index no. of a character", "x")); y=eval(prompt("Enter length of characters","y")); alert(a.substring(x,y)) } function a6() { x=eval(prompt("Enter a no.","x")); alert(a.charAt(x)) } function a7() { x=prompt("Enter a character","x"); alert(a.indexOf(x)) } document.write("<h1>",a, "</h1>") </script> <body> <h2>String Object Properties : </h2> <input type="button" value="toUpperCase" onclick="a1()"><br> <input type="button" value="toLowerCase" onclick="a2()"><br> <input type="button" value="length" onfocus="a3()" ><br> <input type="button" value="Last Index no." onclick="a4()" ><br> <input type="button" value="Substring" onclick="a5()" ><br> <input type="button" value="charAt" onclick="a6()" ><br> <input type="button" value="indexOf" onclick="a7()" > </body> <script> function msg1() { alert("Welcome to the Javascript World"); } function msg2() { alert("Bye! Bye!!"); } </script> <body onload="msg1()" onunload="msg2()"> </body> Example : <script> function showMsg() { document.write(dont move the mouse) </script> <body onMouseMove=showMsg()> Warning : Do not move the mouse

</body> Unload event <html> <head><title>Unload</title> </head> <script> function showMsg() { alert("I told you not to close the page.")} </script> <body onunload="showMsg()"> Warning: Do not close the page </body> </html> Onload event <html> <head><title>On Load</title> </head> <script> function showMsg() {document.bgColor="yellow"} </script> <body onload="showMsg()"> Warning: Do not move the mouse </body> </html> Windows Properties setTimeout :It calls the function after specified time. e.g. <script> function timeoff() { var a=alert("your time is off") } window.setTimeout("timeoff()",1000) </script> 2) setInterval() :- It calls the function after every specified time interval. Eg:<script> function abc() { alert(Working the setInterval) } window.setInterval(abc(),1000) </script> 1)

<script> var index=0 function colchange() { col=new Array("red","blue","black","orange","purple"); document.bgColor=col[index]; index++; if(index>=5) { index=0; } } setInterval("colchange()",1000) </script> Changing inline image of the document on setInterval() <html> <head>

<title>Animals</title> <script language="javascript"> var index=0; function imgchange() { animal=new Array ("Panda.jpg","Dog.jpg","Camel.jpg","Hen.jpg","Lion.jpg","Tiger.jpg","Deer.jpg") myframe.src=animal[index] index++; if (index>=7) { index=0; } } window.setInterval("imgchange()",1000) </script> </head> <body> <img src="Tiger.jpg" NAME="myframe" border="3" height="30%" width="100%"> </body> </html>

<script> var index=0; img=new Array("1.jpg","2.jpg","3.jpg","4.jpg") function imgchange() { myframe.src=img[index] index++; if (index>=4) { index=0; } } setInterval("imgchange()",1000) </script> <body> <img src="1.jpg" name=myframe> </body>

Adding dynamic & interactive effect on a webpage using Javascript (DHTML effect) <html> <head> <title>Text Grow Effect</title>

<style type= text/css> #abc { font-family:"Arial";font-size:10; color:"red" } </style> <script language="javascript"> var size=10; var flag=true; function grow() { if (size<=100 &&flag) { abc.style.fontSize=size; size+=4; //size=size+4 if(size>=100) flag=false;

} else if(size>=10 && !flag) { abc.style.fontSize=size; size -= 4; //size=size-4 if(size<=10) flag=true; } } setInterval("grow()",50) </script> </head> <body> <h1 id="abc">National</h1> </body> </html> Example of Text Animate <script language="javascript"> var index=0 var size=8

var flag=true function animate() { color=new Array("Red","Blue","Green", "Yellow") abc.style.background="gray" abc.style.color=color[index] index++ if(index>=4) { index=0 } if(size<=72 && flag) { abc.style.fontSize=size size++ if(size>72)

flag=false } else if (size>=8 && !flag) { abc.style.fontSize=size size-if(size<8) flag=true } } setInterval("animate()",50) </script> <body> <p id="abc" align="center"> Welcome </p> </body> </html>
<html> <head> <title>Text Glow</title> <style type="text/css"> #abc{ width:100%; color:blue; font-family:Jokerman; text-align:center; } </style>

<script type="text/javascript"> var i=0; var j=true; function glow() { abc.style.filter= "glow(strength="+i+")" if (j==true) i++; if (j==false) i--; if (i==5) j=false; if (i==0) j=true; } setInterval("glow()",50) </script> </head> <body> <h1 id="abc">Glow Text</h1> </body> </html> </html> <html> <head> <title> <style type="text/css"> #abc{font-family:"Verdana"; width: "100"; font-size: "72"; color: "blue"; } </style> <script language="javascript"> var i=0; var flag=true; function shadow() { abc.style.filter="shadow(strength="+i+")" if(flag ==true) i++; if(flag ==false) i--; if(i==15) flag =false; if(i==0) flag =true; } setInterval("shadow()",50) </script> </head> <body> <center> <p id="abc"> Shadow Text </p> </center> </body> </html> </title>

<html> <head><title>Wave & InnerText </title> <style type="text/css"> #abc{ font-family:"Verdana"; width: "100%"; font-size: "72"; font-weight: "bold"; color:"pink"

} </style> <script language="javascript"> var i=0; var count=0; var flag=true; function wave() { abc.style.filter= "wave(strength="+i+")" if (flag==true) i+=2; if(flag==false) i-=2; if(i>=100) { flag=false; if(count==0) { abc.innerText="Welcome to" count=1; } else { abc.innerText="JavaScript" count=0; } } if (i<= -110) flag=true; } setInterval("wave()",10) </script> </head> <body> <center><h1 id="abc"> WAVE TEXT </h1></center> </body> </html> <html> <head> <title>Animate Text </title> <script language="javascript"> var index=0; var size=10; function text() { colors=new Array("red","blue","green","yellow","purple","black") abc.style.background="gray"; abc.style.color=colors[index]; abc.style.fontSize=size; index++; size+=2; if(index==6) index=0; if(size==120) size=10; } function animate() { setInterval("text()",100) } </script> </head> <body onload="animate()"> <h1 id="abc" align=center> welcome</h1> </body> </html>

<html> <head> <title>Animated Text Size Alter </title> <script language="javascript"> var index=0 var size=8 var flag=true function animate() { color=new Array("Red","Blue","Green", "Yellow") abc.style.background="gray" abc.style.color=color[index] index++ if(index==4) { index=0 } if(size<=72 && flag) { abc.style.fontSize=size size++ if(size>=72) flag=false } else if(size>=8 && !flag) { abc.style.fontSize=size size-if(size<=8) flag=true } } setInterval(''animate()'',50) </script> </head> <body> <h1 id="abc" align="center"> Welcome</h1> </body> </html> FORM PROCESSING Javascript provides the form object to enable your scripts to interact with an exercise control over HTML forms. The form object is accused as a property of the document object. o Your browser creates a unique form object for every form that is contained in a document. These objects can be accessed via document.forms[ ] array. o The form object is important because it provides you with access to the forms contained in your documents and allows you to respond to form related events. o Each form in a document is a distinct object. You can refer to a forms element in your code by using the elements name (from the NAME attribute) or the form elements array. The elements array contains an entry for each element such as Checkbox, Radio or Text object in a form. o If multiple objects on the same form have the same name attribute, then an array of the given name is created automatically. Each element in the array represents an individual form object. Elements are indexed in source order starting at 0. For example: if two Text elements and a textarea element on the same form have their Name attribute set to myField, an array with the elements myField[0], myField [1] and myField[2] are created. You need to be aware of this situation in your code and know whether myField refers to a single element or to an array of the elements. o HTML attributes of form and form elements can be accessed as javascript properties of the respective objects. For example: value attribute of Text field of Form (<input type=text>) is accessed as value property in Javascript. Example of Basic Form Processing <html> <head> <title>Form Processing</title> <script language="javascript"> function check() { o

var a=f.T[0].value; var b=f.T[1].value; alert("Name:"+a+"\n"+ "Password:"+b) } </script> </head> <body> <form name="f"> <pre> Name :<input type="text" name="T"> Password:<input type="password" name="T"> <input type="button" value="Click Here" onclick="check()"> <input type="reset" value="Reset"> </pre></form></body></html>

<html> <head> <title>Form Processing</title> <script language="javascript"> function Form_Process() { alert ("User Name:"+ f.T[1].value + "\n\n" + "Password :" +f.T[0].value) } </script> </head> <body><h3>Form Processing </h3> <form name="f"><pre> User Name : <input type="text" name="T"> Password : <input type="password" name="T"> <input type="button" value="Submit" onclick="Form_Process()"> <input type="reset" value="Clear"> </pre> </form> </body> </html> <html> <head> <title>Form processing</title> <script language="javascript"> function processform() { ans="Your name: " +document.forms[0].text1.value+"\n\n"+"Your password: "+document.forms[0].pass1.value; alert(ans); } </script> </head> <body> <h2><center>Basic Form Processing</center></h2> <hr> <form id=forms> Your Name<br> <input type="text" name="text1"> <br> Your Password<br> <input type="password" name="pass1"><br> <input type="button" value="Click Here" onClick=''processform()''> <input type="reset" value="Reset Form"> </form> </body> </html> <html> <head> <title>Digital Clock</title> <script language="javascript"> function Digital()

{ mydate=new Date() var a,b,c; a=mydate.getHours() b=mydate.getMinutes() c=mydate.getSeconds() d.h.value=a d.f.value=b d.s.value=c } setInterval("Digital()",1000) </script> </head> <body> <h1>Digital Clock</h1> <form name="d"> <input type="text" name="h" size="2" readonly> <input type="text" name="m" size="2" readonly> <input type="text" name="s" size="2" readonly> </form> </body> </html>

Example of Customer Billing Form <script> function Total() { f.txtTotal.value=f.txtCurrent.value-f.txtPrevious.value } function Amount() { if (f.txtTotal.value<=100) { f.txtAmount.value=180 } else { f.txtAmount.value=parseInt(180+1.8*(f.txtTotal.value-100)) } } function TSC() {

f.txtTSC.value=parseInt(0.1*f.txtAmount.value) } function VAT() { f.txtVAT.value=parseInt(0.13*f.txtAmount.value) } function Net() { f.txtNet.value=parseInt(f.txtAmount.value)+parseInt(f.txtTSC.value)+parseInt(f.txtVAT.value) }

</script> <html> <head> <title>Nepal Telecommunication</title> <script> function Total() { f.T4.value =eval(f.T3.value) -eval(f.T2.value) } function Amount() { if (f.T4.value<=100) { f.T5.value=180; } else { f.T5.value = eval(180+1.8*(f.T4.value-100)) } } function TSC() { f.T6.value=0.1*f.T5.value } function VAT() { f.T7.value= parseInt(0.13*f.T5.value) } function Net() { f.T8.value=eval (f.T5.value) + eval (f.T6.value) + eval (f.T7.value) } </script> </head>

<body> <form name="f"> Example of Salary Distribution Form <script> function IncomeTax() { if (f.txtPost.value=="Manager") { f.txtIncomeTax.value=parseInt (0.07*f.txtBasicSalary.value) } else if (f.txtPost.value=="Supervisor") { f.txtIncomeTax.value=parseInt (0.06*f.txtBasicSalary.value) } else if (f.txtPost.value=="Marketing Officer") { f.txtIncomeTax.value=parseInt (0.05*f.txtBasicSalary.value) } else if (f.txtPost.value=="Secretary") { f.txtIncomeTax.value=parseInt (0.04*f.txtBasicSalary.value) } else { f.txtIncomeTax.value=parseInt (0.02*f.txtBasicSalary.value) } } function SecurityDeposit() { f.txtSecurityDeposit.value=parseInt(0.1*f.txtBasicSalary.value) } function Allowance() { if (f.txtMaritalStatus.value=="Married") { f.txtAllowance.value=parseInt (0.12*f.txtBasicSalary.value) } else { f.txtAllowance.value=parseInt (0.1*f.txtBasicSalary.value) } } function NetSalary() { f.txtNetSalary.value=parseInt(f.txtBasicSalary.value) parseInt(f.txtIncomeTax.value) parseInt(f.txtSecurityDeposit.value)+ parseInt(f.txtAllowance.value) } </script> <body><form name= f>

Example of Mark sheet Entry Form <script language="javascript"> function Total() { f.txtTot.value= parseFloat(f.txtPhy.value) + parseFloat(f.txtChe.value) + parseFloat(f.txtBio.value) + parseFloat(f.txtMath.value) + parseFloat(f.txtEng.value)

} function Remarks() { if (f.txtPhy.value>=35 && f.txtChe.value>=35 && f.txtBio.value>=35 && f.txtMath.value>=35 && f.txtEng.value>=35) { f.txtRem.value="Pass"; } else { f.txtRem.value="Fail"; } } function Percentage() { f.txtPer.value=f.txtTot.value/5 } function Division() { if (f.txtRem.value=="Fail") { f.txtDiv.value="No division" } else if (f.txtPer.value>=75) { f.txtDiv.value="Distinction" } else if (f.txtPer.value>=60) { f.txtDiv.value="First Division" } else if (f.txtPer.value>=45) { f.txtDiv.value="Second Division" } else { f.txtDiv.value="Third Division" } } </script> <body> <form name= f> Online Exam Demo <html> <head><title>Quiz 1</title> <script> function check() { if (f.R1[1] .checked==true) { alert("Correct answer") } else { alert("Wrong answer") } } </script></head> <body> <form name="f"> Which of the following calls the function automatically? <br> <input type="radio" name="R1"> onload<br>

<input type="radio" name="R1"> setInterval<br> <input type="radio" name="R1"> onblur<br> <input type="button" value="Check" onclick="check()"> </form> </body> </html> Example of Form Validation <html> <head> <title>Form Validation</title> <script language="javascript"> function nameValid() { if (f.txtName.value=="") { alert("Name is left blank") f.txtName.focus() } } function passwordValid() { if (f.txtPassword.value=="") { alert("Password is left blank") f.txtPassword.focus() } } </script> </head> <body> <h3>Form Validation</h3> <form name="f"> <pre> Name : <input type="text" name="txtName" onblur="nameValid()"> Password: <input type= "password" name="txtPassword" onblur="passwordValid()"> <input type="button" value="Submit"> <input type="Reset" value="Clear"> </pre> </form> </body> </html> Form Validation <script> function formvalid() { var e=f.Email.value var pwd=f.Password.value if (f.Fname.value=="") { alert("Please enter your first name") f.Fname.focus() } else if (isNaN(f.Fname.value)==false) { alert("Only text allowed") f.Fname.focus() } else if (f.Lname.value=="") { alert("Please enter your last name") f.Lname.focus() }

else if (f.R1[0].checked==false && f.R1[1].checked==false)

{ alert("please select your gender") f.R1[0].focus() }

else if (f.Email.value=="") { alert("Please enter your Email") f.Email.focus() } else if (e.indexOf("@",1)==-1 || e.indexOf(".",3)==-1) { alert("Invalid email") f.Email.focus() }

else if (pwd=="") { alert ("Password field can't be left as blank") f.Password.focus() } else if (pwd.length<6) { alert ("The password you entered should be minimum 8 characters") f.Password.focus() } else if (pwd.indexOf("@")==-1 && pwd.indexOf("_")==-1 && pwd.indexOf(".")==-1) { alert ("The password you entered is invalid") f.Password.focus() }

else if (f.Password.value!=f.Password0.value) { alert ("Password mismatched") f.Password0.focus() } else { win=open("","","tool bar=no") win.document.write("Your name:"+f.Fname.value) } } </script> Registration Forms Validation <script> function formvalid() { var e=f.txtEmail.value var p=f.txtPassword.value var r=f.txtRepassword.value if (f.txtFname.value=="") { alert("First name field cannot be left blank") f.txtFname.focus()

} else if (isNaN(f.txtFname.value)==false) { alert("First name field must be in text") f.txtFname.focus() } else if (f.txtLname.value=="") { alert("Last name field cannot be left blank") f.txtLname.focus() } else if (isNaN(f.txtLname.value)==false) { alert("Last name field must be in text") f.txtLname.focus() } else if(f.txtAge.value=="") { alert("Age field cannot be left blank") f.txtAge.focus() } else if(f.R1[0].checked==false && f.R1[1].checked==false) { alert("Please check your gender") f.R1[0].focus() } else if(e=="") { alert("Email field cannot be left blank") f.txtEmail.focus() } else if(e.indexOf("@",1)==-1 || e.indexOf(".",3)==-1) { alert("Please enter the valid email") f.txtEmail.focus() } else if(p=="") { alert("Password field cannot be left blank") f.txtPassword.focus() } else if(p.length<6) { alert("The password you entered is less than 6 characters") } else if(r=="") { alert("Re-Password field cannot be left blank") f.txtRepassword.focus() } else if(p!=r) { alert("Password mismatched") f.txtRepassword.focus() } else alert("Form is ready to submit") win=open("","","toolbar=no") win.document.write("<h3 align=center> Registered Information</h3><hr color=blue>") win.document.write("<pre>First Name\t:\t"+f.txtFname.value+"\n") win.document.write("Last Name\t:\t"+f.txtLname.value+"\n") win.document.write("Age\t\t:\t"+f.txtAge.value+"\n") win.document.write("Email\t\t:\t"+f.txtEmail.value+"\n") win.document.write("Password\t:\t"+f.txtPassword.value+"\n </pre") }

</script>

<script> function formvalid() { var a=r.txtName.value var b=r.txtAge.value var c=r.txtEmail.value var d=r.txtPassword.value var e=r.txtRepassword.value if (a=="") { alert ("Name field is left blank") r.txtName.focus() } else if(isNaN(a)==false) { alert("Name should be in text") r.txtName.focus() } else if (b=="") { alert ("Age field is left blank") r.txtAge.focus() } else if (b<10) { alert ("You are under 10") r.txtAge.focus() } else if (c=="") { alert ("Email field is left blank") r.txtEmail.focus() } else if (c.indexOf("@",1)==-1 || c.indexOf(".",3)==-1) { alert ("invalid email") r.txtEmail.focus() } else if (d=="") { alert("Password field is left blank") r.txtPassword.focus() } else if(d.length<=4) { alert ("Enter at least 5 characters") r.txtPassword.focus() } else if (e=="") { alert ("Re-Password field is left blank") r.txtRepassword.focus() } else if(e != d) { alert ("Password mismatched") r.txtRepassword.focus() } else {

alert("Form is ready to submit") win=open("","","toolbar=no") win.document.write("<h3>Registered information</h3>") win.document.write("<pre>Name\t:\t"+a) win.document.write("\nAge\t:\t" +b) win.document.write("\nEmail\t:\t"+c) win.document.write("\nPassword:\t"+d) win.document.write("\nRe-Password:\t"+e+"</pre>") } } </script>

Registration Form Validation <script> function formvalidation() { e=f.Email.value p=f.Password.value rp=f.Repassword.value if (f.Naam.value=="") { alert ("Name field is left empty") f.Naam.focus() } else if (f.Age.value=="") { alert ("Age field is left empty") f.Age.focus() } else if (isNaN(f.Age.value)==true) { alert ("Age field must be in no.") f.Age.focus() } else if (f.Gender[0].checked==false && f.Gender[1].checked==false) { alert ("Please check on your gender") } else if (e=="") { alert ("Email field is left empty") f.Email.focus() } else if (e.indexOf("@",1)==-1 || e.indexOf(".",3)==-1) { alert ("Email is not valid") f.Email.focus() } else if(p=="") { alert ("Password field is left empty") f.Password.focus() } else if (rp=="") { alert ("Re-Password field is left empty") f.Repassword.focus() } else if (p!=rp) { alert ("Password mismatched") f.Password.focus() } else { alert ("Record has been filled successfully") win=open("","","height=250 width=500") win.document.write("<pre><h3 align=center><marquee>Registered Information </marquee></h3><hr color=red><font color=blue>") win.document.write("\nName\t:\t"+f.Naam.value) win.document.write("\nAge\t:\t"+f.Age.value) win.document.write("\nDOB\t:\t") if(f.D1.selectedIndex==1) win.document.write(f.D1.value) else if(f.D1.selectedIndex==2)

win.document.write(f.D1.value) else if(f.D1.selectedIndex==3) win.document.write(f.D1.value) else if(f.D1.selectedIndex==4) win.document.write(f.D1.value) win.document.write("<b> Month </b>") if(f.D2.selectedIndex==1) win.document.write(f.D2.value) else if(f.D2.selectedIndex==2) win.document.write(f.D2.value) win.document.write("<b> Day </b>") if(f.D3.selectedIndex==1) win.document.write(f.D3.value) else if(f.D3.selectedIndex==2) win.document.write(f.D3.value) win.document.write("<b> Year</b>") if (f.Gender[0].checked) { win.document.write("\nGender\t:\t"+f.Gender[0].value) } else { win.document.write("\nGender\t:\t"+f.Gender[1].value) } win.document.write("\nEmail\t:\t"+f.Email.value) win.document.write("\nPassword:\t"+f.Password.value) win.document.write("\nPhoto\t:\t<img src=' "+f.Image.value+" ' height=50 width=50 border=2></font></pre>") } } </script> </head> <body> <form name="f"> <h1>Registration Form</h1> <pre> Name : <input type="text" name="Naam" value="<<Enter your name>>" onClick="this.value=''"> Age : <input type="text" name="Age" value="<<Enter your age>>" onClick="this.value=''"> DOB : <select size="1" name="D1"> <option value="Select One" selected>MM</option> <option value="Jan">Jan</option> <option value="Feb">Feb</option> <option value="March">March</option> <option value="Apr">Apr</option> <option value="May">May</option> <option value="June">June</option> <option value="July">July</option> <option value="Aug">Aug</option> <option value="Sep">Sep</option> <option value="Oct">Oct</option> <option value="Nov">Nov</option> <option value="Dec">Dec</option> </select>Month<select size="1" name="D2"><option>DD</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option><option value="21">21</option><option value="22">22</option><option

value="23">23</option><option value="24">24</option><option value="25">25</option><option value="26">26</option><option value="27">27</option><option value="28">28</option><option value="29">29</option><option value="30">30</option><option value="31">31</option> </select>Day<select name="D3" id="D3"><option selected>YY</option><option value="1970">1970</option><option value="1971">1971</option><option value="1972">1972</option><option value="1973">1973</option><option value="1974">1974</option><option value="1975">1975</option><option value="1976">1976</option><option value="1977">1977</option><option value="1978">1978</option><option value="1979">1979</option><option value="1980">1980</option><option value="1981">1981</option><option value="1982">1982</option><option value="1983">1983</option><option value="1984">1984</option><option value="1985">1985</option><option value="1986">1986</option><option value="1987">1987</option><option value="1988">1988</option><option value="1999">1999</option><option value="2000">2000</option><option value="2001">2001</option><option value="2002">2002</option><option value="2003">2003</option><option value="2004">2004</option><option value="2005">2005</option><option value="2006">2006</option><option value="2007">2007</option><option value="2008">2008</option><option value="2009">2009</option><option value="2010">2010</option><option value="2011">2011</option><option value="2012">2012</option><option value="2013">2013</option><option value="2014">2014</option><option value="2015">2015</option><option value="2016">2016</option><option value="2017">2017</option><option value="2018">2018</option><option value="2019">2019</option><option value="2020">2020</option></select>Year Gender : <input type="radio" name="Gender" value="Male">Male <input type="radio" name="Gender" value="Female"> Female Email :<input type="text" name="Email" value="<<Enter your Email>>" onClick="this.value=''"> Password :<input type="Password" name="Password"> Re-Password :<input type="Password" name="Repassword"> Upload :<input type="file" name="Image"> <input type="button" value="Submit" onClick="formvalidation()"> <input type="reset" value="Reset"> </pre> </form> </body>

You might also like