Professional Documents
Culture Documents
Unit-I Java Script
Unit-I Java Script
Java Script
Server-side Applications vs. Client-side Applications
• server-side applications are applications runs on the Web server
• Clint-side applications are are small applications which are embedded within
the HTML code and executed by the browser.
Server-Side Code
• Languages include Python , PHP, C#, Servlets and JSP;
• Cannot be seen by the user .
• Can only respond to HTTP requests for a particular URL.
Client-Side Code
• Languages used include: HTML, CSS, and Java script.
• Parsed by the user’s browser.
• Reacts to user input.
• Can be seen and edited by the user in full.
What is DHTML?
• Dynamic HyperText Markup Language (DHTML) is a combination of Web
development technologies used to create dynamically changing websites.
• Web pages may include animation, dynamic menus and text effects.
DHTML = HTML + CSS + JavaScript
• HTML defines Web site content through tags (headings, paragraphs, lists, …)
• CSS defines ''styles' for presenting every aspect of an HTML document
• JavaScript defines dynamic behavior
• Programming logic for interaction with the user, to handle events, etc.
What is JavaScript
• JavaScript is an interpreted, client-side, event-based, object
oriented scripting language used to add dynamic interactivity to
web pages and runs in the browser.
• JavaScript is a scripting language designed primarily for creating
dynamic Web pages.
• It is used to add dynamic behavior, store information, and handle
requests and responses on a website
• JavaScript is most commonly used as a client side scripting
language. This means that JavaScript code is written into an
HTML page.
What Can JavaScript Do?
• validate form data
• Performing complex calculations
• Content loading and changing dynamically
• handle events
• read and write HTML elements
• Changing the behaviour dynamically
• Reacting to user actions
History of JavaScript ?
<body>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.write("value of z is" +z);
</script>
</body> </html>
Functions
• A JavaScript function is a block of code designed to perform a
particular task.
• A function is code that is executed when an event fires or a call to that
function is made.
Syntax
function function-name(parameter1, parameter2, parameter3)
{
code to be executed
}
We will define the function in head section and call the function from
the body
<html><head><script>
function add(){
var a,b,c;
a=Number(document.getElementById("first").value);
b=Number(document.getElementById("second").value);
c= a + b;
document.getElementById("answer").value= c;
}
</script></head><body>
First Value:<input type="text" id="first"><br>
First Value:<input type="text" id="second"><br>
Result:<input type=“text” id="answer"><br>
<button onclick="add()">Add</button>
</body></html>
Conditional Statements
• Conditional statements allow you to take different actions depending upon different
statements.
• There are three types of conditional statement
1. if statements
2. if...else statements
3. else if ladder
if Statements
• if statements allow code to be executed when the condition specified is true; if the
condition is true then the code in the curly braces is executed.
Here is the syntax for an if statement:
if (condition)
{
code to be executed if condition is true
}
if . . . else Statements
If the conditions specified are met, then first block of code will be executed ;
otherwise second block of code will be executed .
The syntax is as follows:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}
else if ladder Statements
The syntax is as follows:
if (condition)
{
code to be executed if condition is true
}
else if (condition)
{
code to be executed if condition is false
}
else{
code to be executed if condition is false
}
if . . . else Statements
<html>
<body>
<script>
date=new Date();
time=date.getHours();
if(time<12)
document.write("<h1>Good Morning");
else
document.write("<h1>Good Evening");
</script>
</body>
</html>
JavaScript Loops
• Looping statements are used to execute the same block of code
a specified number of times.
1. while
2. do…while
3. for
while loop
• A while loop runs the same block of code while or until a
condition is true.
The syntax is as follows:
while (condition)
{
code to be executed
}
<html><body>
<h1 style=color:blue>Reversenumber</h1>
<script>
var no, r, rev= 0;
no= prompt("enter number");
while (no>0) {
r=no%10;
rev=rev*10+r;
no=Math.floor(no/10);
}
document.write("<h1> Reverse of a Given No is"+rev);
</script></body></html>
do . . . while
• A do ... while loop executes a block of code once and then
checks a condition.
• For as long as the condition is true it continues to loop.
• So, whatever the condition, the loop runs at least once
do
{
code to be executed
}
while (condition)
<html><body>
<h1 style=color:blue>MultiplicationTable</h1>
<script>
i = 1;
var n= prompt("enter number");
do {
m=i*n;
document.write(n + " x " + i + "=" + m + "<br />" );
i ++
}while (i < 11)
</script>
</body></html>
for
• The for statement executes a block of code a specified number of times;
• you use it when you know how many times you want the code to be
executed
Method Description
getFullYear() returns the year in 4 digit e.g. 2015.
Method Description
abs() Returns the absolute value of a number.
ceil() Returns the smallest integer greater than or equal to a number.
var arrayname=[value1,value2.....valueN];
var arrayname=new Array();
var emp=new Array("Jai","Vijay","Smith");
Cont …
• Javascript array length property returns the number of elements in an
array.
Syntax:
array.length;
Ex:
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
Methods
Method Description
concat() Returns a new array comprised of this array joined with other
array(s) and/or value(s).
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the
new length of the array.
reverse() Reverses the order of the elements of an array -- the first becomes
the last, and the last becomes the first.
shift() Removes the first element from an array and returns that element.
slice() Extracts a section of an array and returns a new array.
sort() Sorts the elements of an array
unshift() Adds one or more elements to the front of an array and returns the
new length of the array.
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write("<h1> Before Array operations:</h1>"+fruits);
fruits.pop();
document.write("<h1> After POP():</h1>"+fruits);
fruits.push("Kiwi");
document.write("<h1> After Push():</h1>"+fruits);
fruits.shift();
document.write("<h1> After shift():</h1>"+fruits);
fruits.unshift("Sapota");
document.write("<h1> After shift():</h1>"+fruits);
var num=["2","1","3"]
var my= num.concat(fruits);
document.write("<h1> After concat():</h1>"+my);
document.write("<h1> After reverse:</h1>"+my.reverse());
document.write("<h1> After sort:</h1>"+my.sort());
JavaScript Strings
Method Description
charAt() Returns the character at the specified index.
concat() Combines the text of two strings and returns a new string.
replace() It replace the matched substring with a new substring.
slice() Extracts a section of a string and returns a new string.
substr() Returns the characters in a string beginning at the specified
location through the specified number of characters.
toLowerCase() Returns the calling string value converted to lower case.
toUpperCase() Returns the calling string value converted to uppercase.
Example
<script>
var s1="javascript";
document.write("<h1>string length:</h1>"+s1.length);
document.write("<br>"+s1.charAt(2));
var s2="concat example";
var s3=s1.concat(s2);
document.write("<h1>after concat:</h1>"+s3);
var s4=s3.toUpperCase();
document.write("<h1>after Upper case:</h1>"+s4);
var s5=s4.toLowerCase();
document.write("<h1>after lower case:</h1>"+s5);
var s6=s5.slice(2,5);
document.write("<h1>after slice:</h1>"+s6);
var s7=s5.substr(2,5);
document.write("<h1>after substring:</h1>"+s7);
</script>
Dialog Boxes
Method Description
<html>
<body>
<script>
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);
}
</script>
<input type="button" onclick="msg()" value="Tryit">
</body>
</html>
Document Object Model
Method Description
write("string") writes the given string on the doucment.
writeln("string") writes the given string on the doucment with
newline character at the end.
getElementById() returns the element having the given id
value.
Accessing field value by document object
• document.form1.name.value is used to get the value of name field.
• Here, document is the root element that represents the html document.
• form1 is the name of the form.
• name is the attribute name of the input text.
• value is the property, that returns the value of the input text.
<script >
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
HTML Events
Event Description
onclick The user clicks an HTML element(button)
• This is the most frequently used event type which occurs when a user
clicks the html element like button.
Syntax:
onclick= function()
Ex:
<input type="button" onclick="printvalue()" value="print name"/>
Example
<html>
<body>
<script>
function displayDate() {
document.write(Date());
}
</script>
<p>Click the button to display the date.</p>
<input type="button" onclick="displayDate()" value=click>
</body>
</html>
onsubmit Event type
• onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
<html><body>
<script>
function validateform(){
var name=document.myform.name.value;
If(name==""){
alert("Name can't be blank");
return false; }}
</script>
<body>
<form name="myform" method="post" onsubmit="validateform()" >
Name: <input type="text" name="name"><br/>
<input type="submit" value="Submit">
</form> </body></html>
JavaScript Form Validation
• It is important to validate the form submitted by the user because it can
have in appropriate values. So validation is must.
• The JavaScript provides you the facility the validate the form on the client
side so processing will be fast than server-side validation.
• So, most of the web developers prefer JavaScript form validation.
• Through JavaScript, we can validate name, password, email, date, mobile
number etc fields.
What is form validation?
• Form validation is the process of making sure that data supplied by the
user using a form, meets the criteria set for collecting data from the user
User Name Validation <html><head>
Rules: <script type="text/javascript">
function validation()
1. Name not empty {
var a = document.form.name.value;
if(a=="")
2. Only Characters. {
alert("Please Enter Your Name");
3. Must be 5 to 15 Characters. return false;
}
if(!isNaN(a))
{
alert("Please Enter Only Characters");
return false;
}
if ((a.length < 5) || (a.length > 15))
{
alert("Your Character must be 5 to 15 Character");
return false;}}
</script></head>
<body>
<form name="form" method="post" onsubmit="return validation()">
Your Name:<input type="text" name="name"">
<input type="submit" name="sub" value="Submit">
</form></body></html>
Password Validation <html> <head><script>
function CheckPassword()
Rules: {
input=document.form1.text1.value;
1. 6 to 20 characters which contain at var pass= /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/;
least one numeric digit, one if(input.match(pass))
uppercase and one lowercase {
letter alert("Correct")
return true;
}
else
{
alert('Wrong...!')
return false;
} }
</script> </head>
<body>
<h2>Input Password and Submit [6 to 20 characters which
contain at least one numeric digit, one uppercase and one
lowercase letter]</h2>
<form name="form1" action="#">
Enter Password <input type="text" name="text1"/>
<input type="submit" name="submit" value="Submit"
onclick="CheckPassword()"/>
</form> </body> </html>
Retype Password Validation
<html><head><script>
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;}}
</script></head>
<body>
<form name="f1" onsubmit="matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form></body></html>
Phone Number Validation <html><head><script>
function validate(){