Vous êtes sur la page 1sur 75

JavaScript

Client Side Scripting

Client Side Scripting


Client side scripting is the scripting language where the scripts are executed by the browser and the results are thrown to the active page. Client side scripting is fast but not secure. It can not use the database as it does not communicate with the server.

What can we do with it?


Validating

user inputs Adding basic dynamic property to the page It can be used to add the special effect to the page. But JavaScript can be disabled from the browser.

A Basic Example
<html> <head> <title>First JavaScript</title> </head> <body> <h1>My First Web Page</h1> <script type="text/javascript"> document.write("<p>" + Date() + "</p>"); </script> </body> </html>

Output

Referring to an element
<html> <head> <title>Changing HTML Elements</title> </head> <body> <h1>My First Web Page</h1> <p id="demo" style="font-family: &quot;Berlin Sans FB&quot;; font-size: large; font-weight: bold; font-style: italic; color: #FF00FF; background-color: #00FFFF">This is a paragraph.</p> <script type="text/javascript"> document.getElementById("demo").innerHTML=Date(); </script> </body> </html>

Output

External JavaScript
<html> <head> <title>External JavaScript</title> <script type="text/javascript" src="test.js"></script> </head> <body> <h1>My Web Page</h1> <p id="demo" style="font-family: &quot;Berlin Sans FB&quot; fontsize: large; font-weight: bold; font-style: italic; color: #FF00FF; background-color: #00FFFF">This is a paragraph.</p> <button type="button" onclick="displayDate()">Display Date</button> </body> </html>

Interacting with the script using control


<html> <head> <title>JavaScript in &lthead&gt</title> <script type="text/javascript"> function displayDate() { document.getElementById("demo").innerHTML= Date(); } </script> </head>

Body Part
<body> <h1>My First Web Page</h1> <p id="demo" style="font-family: &quot;Berlin Sans FB&quot;font-size: large; font-weight: bold; font-style: italic; color: #FF00FF; backgroundcolor: #00FFFF">This is a paragraph.</p> <button type="button" onclick="displayDate()">Display Date</button> </body> </html>

Click Here

Making element
<html> <head> <title>JavaScript Code</title> </head> <body> <script type="text/javascript"> document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); </script> </body> </html>

Making element Part 2


<script> var my_div = null; var newDiv = null; function addElement () { // create a new div element // and give it some content var newDiv = document.createElement("div"); var newContent = document.createTextNode("Hi there and greetings!"); newDiv.appendChild(newContent); //add the text node to the newly created div. // add the newly created element and it's content into the DOM my_div = document.getElementById("org_div1"); document.body.insertBefore(newDiv, my_div);

</script>

<body onload="addElement()"> <div id='org_div1'> The text above has been created dynamically.</div> </body> </html>

Creating element with dynamic data


<html> <head> <title>JavaScript Variables</title> </head> <body> <script type="text/javascript"> var x=5; var carname="Volvo"; document.write("<p>Value of x is:: "+x+"</p>"); document.write("<p>Carname is:: "+carname+"</p>"); </script> </body> </html>

Arithmetic Operator
Arithmetic operators are used to perform arithmetic between variables and/or values. Assume y=5 + Addition x=y+2 x=7 - Subtraction x=y-2 x=3 * Multiplication x=y*2 x=10 / Division x=y/2 x=2.5 % Modulus x=y%2 x=1 ++ Increment x=++y x=6 y=6 x=y++ x=5 y=6 -- Decrement x=--y x=4 y=4 x=y-x=5 y=4

Arithmetic Operator Cont..


Operator Used As Detail x=x+y x=x-y x=x*y x=x/y x=x%y Example

=
+= -= *= /= %=

x=y
x+=y x-=y x*=y x/=y x%=y

X=5
x=15 x=5 x=50 x=2 x=0

Operators

Assume x=6 and y=3

Retrieving value from controls


<html> <head> <title>Retrieve Value From Text Box</title> <script type="text/javascript"> function displayName() { var name=document.getElementById("txtFullName").value; alert("Your name is:: "+name); } </script> </head>

Body (Called from)


<body> <form> Enter your full name:: <input type="text" name="txtFullName" id="txtFullName"> <input type="button" value="Submit" onclick="displayName()"> </form> </body> </html>

Click Here

Simple Addition
<html> <head> <title>ADD Example</title> <script type="text/javascript"> function displayAddResult() { var no1=parseInt(document.getElementById("txtFirstNo").value); var no2=parseInt(document.getElementById("txtSecondNo").value); alert("Addition result of "+no1+" and "+no2+" is:: "+(no1+no2)); }

Cont..
</script> </head> <body> <form> Enter first no:: <input type="text" name="txtFirstNo" id="txtFirstNo"><br> Enter second no:: <input type="text" name="txtSecondNo" id="txtSecondNo"><br> <input type="button" value="ADD" onclick="displayAddResult()"> </form> </body> </html>

Click Here

Output

Conditional Statements
if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true }

Else If
if...else if....else statement - use this statement to select one of many blocks of code to be executed if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if neither condition1 nor condition2 is true }

Example
<script type="text/javascript"> var d = new Date() var time = d.getHours() if (time<10) { document.write("<b>Good morning</b>"); } else if (time>10 && time<16) { document.write("<b>Good day</b>"); } else { document.write("<b>Hello World!</b>"); } </script>

Switch Statement
switch statement - use this statement to select one of many blocks of code to be executed switch(n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 }

Example
<script type="text/javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 5: document.write("Finally Friday"); break; case 6: document.write("Super Saturday"); break; case 0: document.write("Sleepy Sunday"); break; default: document.write("I'm looking forward to this weekend!"); } </script>

Get a greetings from your page

<script type="text/javascript"> //If the time is less than 10, you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("Good morning!"); } else { document.write("Good day!"); } </script>

Example with Switch


<script type="text/javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 5: document.write("Finally Friday"); break; case 6: document.write("Super Saturday"); break; case 0: document.write("Sleepy Sunday"); break; default: document.write("I'm looking forward to this weekend!"); } </script>

Popups
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box
An

alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed.

alert("sometext");

Confirm Box
A

confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
confirm("sometext");

Example

<html> <head> <script type="text/javascript"> function show_confirm() { var r=confirm("Press a button"); if (r==true) { alert("You pressed OK!"); } else { alert("You pressed Cancel!"); } } </script> </head> <body> <input type="button" onclick="show_confirm()" value="Show confirm box" /> </body> </html>

Prompt Box
A

prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
prompt("sometext","defaultvalue");

Example

<html> <head> <script type="text/javascript"> function show_prompt() { var name=prompt("Please enter your name","Harry Potter"); if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?"); } } </script> </head> <body> <input type="button" onclick="show_prompt()" value="Show prompt box" /> </body> </html>

Functions
A function contains code that will be executed by an event or by a call to the function. function functionname(var1,var2,...,varX) { some code }

Function Example

<html> <head> <script type="text/javascript"> function product(a,b) { return a*b; } </script> </head> <body> <script type="text/javascript"> document.write(product(4,3)); </script> </body> </html>

Loops
A

loop is a sequence of statements which is specified once but which may be carried out several times in succession.

The For Loop The While Loop The do...while Loop

For Example
for { document.write("The

(i=0;i<=5;i++)

number is " + i); document.write("<br />"); }

A very important tool


<script type="text/javascript"> function howMany (selectItem) { var numberSelected=0

for (var i=0; i < selectItem.options.length; i++) { if (selectItem.options[i].selected == true) numberSelected++; }


return numberSelected;

}
</script>

Multiple
<form name="selectForm"> <p>Choose some book types, then click the button below:</p> <select multiple name="bookTypes" size="8"> <option selected> Classic </option> <option> Information Books </option> <option> Fantasy </option> <option> Mystery </option> <option> Poetry </option> <option> Humor </option> <option> Biography </option> <option> Fiction </option> </select> <input type="button" value="How many are selected? onclick="alert('Number of options selected: ' + howMany(document.selectForm.bookTypes))"> </form>

While Loop

<html> <body> <script type="text/javascript"> var i=0; while (i<=5) { document.write("The number is " + i); document.write("<br />"); i++; } </script> </body> </html>

Array in JavaScript
<script type="text/javascript">

var month_array = new Array();


month_array[0] = "January"; month_array[1] = "February"; month_array[2] = "March"; month_array[3] = "April"; month_array[4] = "May"; month_array[5] = "June"; month_array[6] = "July"; month_array[7] = "August"; month_array[8] = "September"; month_array[9] = "October"; month_array[10] = "November"; month_array[11] = "December"; document.write('<select name="day">'); var i = 1; while ( i <= 31 ) { document.write('<option value=' + i + '>' + i + '</option>'); i++; }

Example cont..
document.write('</select>');

document.write('<select name="month">'); var i = 0; while ( i <= 11 ) { document.write('<option value=' + i + '>' + month_array[i] + '</option>'); i++; } document.write('</select>');
document.write('<select name="year">'); var i = 1900; while ( i <= 2005 ) { document.write('<option value=' + i + '>' + i + '</option>'); i++; } document.write('</select>'); </script>

Do..While Loop
<html> <body> <script type="text/javascript"> var i=0; do { document.write("The number is " + i); document.write("<br />"); i++; } while (i<=5); </script> </body> </html>

Break and Continue


<html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==3) { break; } document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==3) { continue; } document.write("The number is " + i); document.write("<br />"); } </script> </body> </html>

For Each Equivalent Loop


var person={fname:"John",lname:"Doe",age:25}; for (x in person) { document.write(person[x] + " "); }

Eval
<html> <head> <script language="JavaScript"> a=eval("5*6*2"); document.write("The value of expretion is: : "+a) </script> </head> <body> <br /> It is a JavaScript programe. </body> </html>

A different approach
<html> <head> <script type="text/javascript"> function getValue() { var selected_index = document.getElementById("country").selectedIndex; alert(selected_index); if(selected_index > 0) { var selected_option_value = document.getElementById("country").options [selected_index].value; alert(selected_option_value); var selected_option_text = document.getElementById("country").options[selected_index].text; alert(selected_option_text); } else { alert("Please select a country from the drop down list"); } } </script> </head>

Body cont..
<body> <form> <select size="1" id="slt_country" name="country"> <option value=""> - Select - </option> <option value="AF">Afghanistan</option> <option value="AL">Albania</option> <option value="DZ">Algeria</option> <option value="ZM">Zambia</option> <option value="ZW">Zimbabwe</option> </select> <input type="button" value="OK" onClick="getValue()"> </form> </body> </html>

Events
<html> <head> <title>PrettyPretty</title> <script type="text/javascript"> document.onclick=changeElement; function changeElement() { var div = document.getElementById("div1"); div.style.backgroundColor="#00f"; div.style.width="500px"; div.style.color="#fff"; div.style.height="200px"; div.style.paddingLeft="50px"; div.style.paddingTop="50px"; div.style.fontFamily="Verdana";

Cont..
div.style.fontSize="2em"; div.style.border="3px dashed #ff0"; div.style.position="absolute"; div.style.left="200px"; div.style.top="100px"; div.style.textDecoration="underline"; } </script> </head> <body> <div id="div1"> This is a DIV element. Click me to see the change. </div> </body> </html>

Event list

String Class
<html> <head> <title>String Object Method Example</title> </head> <body> <script type="text/javascript"> var s1=new String("This program shows the usage of String methods"); document.write(s1+"<br>"); document.write(s1.toLowerCase()+"<br>"); document.write(s1.toUpperCase()+"<br>"); document.write(s1.indexOf("the")+"<br>"); document.write(s1.charAt(6)+"<br>"); var s2=new String(Console"); var s3=new String(Management"); var s4=s2.concat(s3); document.write(s4+"<br>") </script> </body> </html>

Output
This

program shows the usage of String methods this program shows the usage of string methods THIS PROGRAM SHOWS THE USAGE OF STRING METHODS 19 R ConsoleManagement

String Cont..
<html> <head> <title>String Object Method Example</title> </head> <body> <script type="text/javascript"> var s1=new String("Welcome my dear students"); document.write(s1.strike()+"<br>"); document.write(s1.italics()+"<br>"); document.write(s1.sub()+"<br>"); document.write(s1.sup()+"<br>"); document.write(s1.fontcolor("red")+"<br>"); document.write(s1.fontsize(20)+"<br>"); </script> </body> </html>

Date
<html> <head> <title>String Object Method Example</title> </head> <body> <script type="text/javascript"> var today=new Date(); document.write("<h1>"+today+"</h1><br>"); document.write("<h1>"+today.getTime()+"</h1><br>"); document.write("<h1>"+today.getSeconds()+"</h1><br>"); document.write("<h1>"+today.getMinutes()+"</h1><br>"); document.write("<h1>"+today.getHours()+"</h1><br>"); document.write("<h1>"+today.getDay()+"</h1><br>"); document.write("<h1>"+today.getDate() +"</h1><br>"); document.write("<h1>"+today.getMonth()+"</h1><br>"); document.write("<h1>"+today.getFullYear()+"</h1><br>"); </script> </body> </html>

Clock
<html> <head> <script type="text/javascript"> function startTime() { var today=new Date(); var h=today.getHours(); var m=today.getMinutes(); var s=today.getSeconds(); // add a zero in front of numbers<10 m=checkTime(m); s=checkTime(s); document.getElementById('txt').innerHTML=h+":"+m+":"+s; t=setTimeout('startTime()',500); }

Cont..
function checkTime(i) { if (i<10) { i="0" + i; } return i; } </script> </head> <body onload="startTime()"> <div id="txt"></div> </body> </html>

Array Class
<html> <head> <title>Arrray Methods</title> </head> <body> <script type="text/javascript"> Array1=new Array(1,2,3,4,5) Array2=['a','b','c','d','e'] Array3=[4,2,6,7,9] document.write("First Array is:"+Array1+"<br>")//1 2 3 4 5 document.write("Second Array is:"+Array2+"<br>")//a b c d e document.write("Third Array is:"+Array3+"<br>")//4 2 6 7 9 document.write(Array1.concat(Array2)+"<br>")//1 2 3 4 5 a b c d e document.write(Array2.join('-')+"<br>")//a- b- c- d- edocument.write(Array2.reverse()+"<br>")//e d c b a document.write(Array3.sort()+"<br>")//2 4 6 7 9 </script> </body> </html>

Sorting
<html> <head> <title> String Shorting </title> </head> <body> <script language="JavaScript"> var arr=new Array("Arindam","Santanu","Milan"); document.write("Before sorting:<br>"+arr+"<br>"); document.write("After sorting:<br>"+arr.sort()); </script> </body> </html>

Math Class
<html> <head> <title>Math Object Properties and Methods Example</title> </head> <body> <script type="text/javascript"> document.write("Math Properties"+"<br>"+"<br>") document.write("Value of E: "+Math.E+"<br>") document.write("Value of PI: "+Math.PI+"<br>") document.write("Value of LOG10E: "+Math.LOG10E+"<br>") document.write("Math Methods"+"<br>"+"<br>") document.write("Value of Math.ceil(12.345): "+Math.ceil(12.345)+"<br>") document.write("Value of Math.round(12.345): "+Math.round(12.345)+"<br>") document.write("Value of Math.floor(12.345): "+Math.floor(12.345)+"<br>") document.write("Value of Math.cos(30): "+Math.cos(30)+"<br>") document.write("Value of Math.sin(0.5): "+Math.sin(0.5)+"<br>") document.write("Value of Math.pow(5,2): "+Math.pow(5,2)+"<br>") document.write("Value of Math.random(): "+Math.random()+"<br>") </script> </body> </html>

User Defined Class


<html> <head> <title>Own Object</title> </head> <body> <script type="text/javascript"> function car(make,model,year) { this.make=make; this.model=model; this.year=year; this.displayCar=displayCar; } function displayCar() { var result="A beautiful "+this.make+" "+this.modle+" of year "+this.year; document.write(result); } myCar=new car("Maruti","800 AC",2000); myCar.displayCar(); </script> </body> </html>

Window Class
<html> <head> <title>Opening and Closing of Child Window</title> <script type="text/javascript"> var w1=null; function createWindow() { w1=window.open(); w1.document.write("Welcome to Google"); } function closeWindow() { if(w1) { w1.close(); w1=null; } } </script> </head> <body> <form> <input type="button" value="Open Google" onClick="createWindow()"> <input type="button" value="Close Google" onClick="closeWindow()"> </form> </body> </html>

Form Validation
<html> <head> <script type="text/javascript"> function validate_required(field,alerttxt) { with(field) { if (value==null||value=="") { alert(alerttxt); return false; } else { return true; } } }

Cont..
function validate_form(thisform) { with (thisform) { if (validate_required(email,"Email must be filled out!")==false) { email.focus(); return false; } } } </script> </head> <body> <form action="a.html" onsubmit="return validate_form(this)" method="post"> Email: <input type="text" name="email" size="30"> <input type="submit" value="Submit"> </form> </body> </html>

Cont..
<html> <head> <title>Password Check</title> <script language="JavaScript"> function checkForm() { if(document.f1.cst_pword.value=="") { alert("Please enter Password") document.f1.cst_pword.focus() return false } if(document.f1.cpword.value=="") { alert("Please enter Confirm Password") document.f1.cpword.focus() return false }

Cont..
if(document.f1.cst_pword.value!=document.f1.cpword.value) { alert("Password and Confirm Password should be same") document.f1.cpword.focus() return false } } </script> </head> <body> <form method="post" action="a.html" name="f1"> Password:<input type="password" name="cst_pword" /><br /> Confirm Password:<input type="password" name="cpword" /><br /> <input type="submit" name="check" value="Submit" onclick ="return checkForm()" /> </form> </body> </html>

Thank You

Vous aimerez peut-être aussi