Unit 3

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 80

UNIT 3

Scripting
Introduction to Java script
• JavaScript is a dynamic programming
language.

• It is most commonly used as part of web


browsers, whose implementations allow
client-side scripts to interact with the user,
control the browser and alter the document
content that is displayed.
• JavaScript was developed at Netscape.

• It was originally called LiveScript.

• Designed primarily for adding interactivity to


Web pages and creating Web applications.
JavaScript is:

• JavaScript is a lightweight, interpreted


programming language
• Designed for creating network-centric
applications
• Complementary to and integrated with HTML
USES OF JAVASCRIPT

• Create pages dynamically


Based on the user's choices, the date, or other
external data JavaScript can produce pages that
are customized to the user.

• Interact with the user


It can do some processing of forms and can
validate user input when the user submits the
form.
JavaScript Syntax

• A JavaScript consists of JavaScript statements


that are placed within the <script>... </script>
HTML tags in a web page.

• You can place the <script> tag containing your


JavaScript anywhere within you web page but
it is preferred way to keep it within the
<head> tags.
• The <script> tag alert the browser program to
begin interpreting all the text between these
tags as a script.
• So simple syntax of your JavaScript will be as
follows

<script ...>
JavaScript code
</script>
The script tag takes two important attributes:
• language: This attribute specifies what
scripting language you are using.
• type: Indicates the scripting language in use
and its value should be set to
"text/javascript".

<script language="javascript"
type="text/javascript">
JavaScript code
</script>
First JavaScript code
<!DOCTYPE html>
<html>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try
it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Par
agraph changed.";
}</script></body></html>
External javascript
• External file -myScript.js
function myFunction() {
document.getElementById("demo").innerHT
ML = "Paragraph changed.";
}
Html page-
<head>
<script src="myScript.js"></script></head>
JavaScript variable

• You should not use any of the JavaScript


reserved keyword as variable name.

• JavaScript variable names should not start with a


numeral (0-9). They must begin with a letter or
the underscore character.

• JavaScript variable names are case sensitive.


Statements
• In HTML, JavaScript statements are
"instructions" to be "executed" by the web
browser.
• Most JavaScript programs contain many
JavaScript statements.
• The statements are executed, one by one, in
the same order as they are written.
• Semicolons separate JavaScript statements.
if statement
The if statement is the fundamental control
statement that allows JavaScript to make
decisions and execute statements
conditionally.

Syntax:
if (expression){
Statement(s) to be executed if expression is true
}
if...else statement
The if...else statement is the next form of control
statement that allows JavaScript to execute
statements in more controlled way.

Syntax:
if (expression){
Statement(s) to be executed if expression is true
}
else{
Statement(s) to be executed if expression is false
}
SWITCH STATEMENT

The basic syntax of the switch statement is to give


an expression to evaluate and several different
statements to execute based on the value of the
expression.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The while Loop

The most basic loop in JavaScript is the while


loop.

Syntax:
while (expression){
Statement(s) to be executed if expression is true
}
The do...while Loop
The do...while loop is similar to the while loop
except that the condition check happens at
the end of the loop. This means that the loop
will always be executed at least once, even if
the condition is false.

do{
Statement(s) to be executed;
}
while (expression);
The for Loop
The for loop is the most compact form of looping
and includes the following three important parts:
• The loop initialization where we initialize our
counter to a starting value. The initialization
statement is executed before the loop begins.
• The test statement which will test if the given
condition is true or not. If condition is true then
code given inside the loop will be executed
otherwise loop will come out.
• The iteration statement where you can increase
or decrease your counter.
for (initialization; test condition; iteration
statement){
Statement(s) to be executed if test condition is
true
}
Comments
• /* This is a comment */

• // This is a one-line comment

• <!-- This is treated as a one-line comment- ->


Functions
• A JavaScript function is defined with the
function keyword, followed by a name,
followed by parentheses ().
• Function names can contain letters, digits,
underscores, and dollar signs (same rules as
variables).
• The parentheses may include parameter
names separated by commas: (parameter1,
parameter2, ...)
•The code to be executed, by the function, is
placed inside curly brackets: {}

function name(parameter1, parameter2,


parameter3) {
code to be executed
}
• Function parameters are the names listed in
the function definition.

• Function arguments are the real values


received by the function when it is invoked.

• Inside the function, the arguments are used as


local variables.
Function Definition
<script type="text/javascript">
<!--
function functionname(parameter-list)
{
statements
}
//-->
</script>
Calling a Function
<script type="text/javascript">
<!--
display();
//-->
</script>
Events
Events are things that happen, actions, that are
associated with an object.
• onLoad - occurs when a page loads in a browser
• onUnload - occurs just before the user exits a
page
• onMouseOver - occurs when you point to an
object
• onMouseOut - occurs when you point away from
an object
• onSubmit - occurs when you submit a form
• onClick - occurs when an object is clicked
Examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
onchange
<html>
<body>

Enter some text: <input type="text" name="txt" value="Hello"


onchange="myFunction(this.value)">

<script>
function myFunction(val) {
alert("The input value has changed. The new value is: " +
val);
}
</script>

</body>
</html>
onclick
<script>
function inform(){
alert("You have activated me by clicking the grey
button! Note that the event handler is added
within the event that it handles, in this case, the
form button event tag")
}
</script>

<form>
<input type="button" name="test" value="Click me"
onclick="inform()">
</form>
onsubmit
<html> <head>
<script type="text/javascript">
<!-- function validate()
{ all validation goes here ......... return either true
or false } //-->
</script>
</head> <body>
<form method="POST" onsubmit="return
validate()">
<input type="submit" value="Submit" />
</form> </body> </html>
onload
<html>
<head><title>Body onload example</title>
</head>
<body onload="alert('This page has finished
loading!')">
Welcome to my page
</body>
</html>
onmouseover
<html>
<head>
<script type="text/javascript">

function over() {
document.write ("Mouse Over");
}
</script>

</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
onreset
<html><body>
<p>When you reset the form, a function is triggered
which alerts some text.</p>
<form onreset="myFunction()">
Enter name: <input type="text">
<input type="reset"></form>
<script>
function myFunction() {
alert("The form was reset");
}
</script>
</body></html>
Form Validation
Form validation normally used to occur at the
server, after the client had entered all the
necessary data and then pressed the Submit
button. If the data entered by a client was
incorrect or was simply missing, the server
would have to send all the data back to the
client and request that the form be
resubmitted with correct information. This
was really a lengthy process which used to put
a lot of burden on the server.
JavaScript in Form Validation
JavaScript provides a way to validate form's data
on the client's computer before sending it to
the web server. Form validation generally
performs two functions:
• Basic Validation
• Data Format Validation
• Basic Validation − First of all, the form must be
checked to make sure all the mandatory fields
are filled in. It would require just a look
through each field in the form and check for
data.

• Data Format Validation − Secondly, the data


that is entered must be checked for correct
form and value. Your code must include
appropriate logic to test correctness of data.
HTML code for form
<html>
<head>
<title>JavaScript Form Validation using a registration
form</title>
<script src="registration-form-validation.js"></script>
</head>
<body>
<h1>Registration Form</h1>
<form name='registration' onSubmit="return
formValidation();">
<ul>
<li><label for="userid">User id:</label></li>
<li><input type="text" name="userid" size="12"
/></li>
<li><label for="passid">Password:</label></li>
<li><input type="password" name="passid"
size="12" /></li>
<li><label for="username">Name:</label></li>
<li><input type="text" name="username" size="50"
/></li>
<li><label for="address">Address:</label></li>
<li><input type="text" name="address"
size="50" /></li>
<li><label for="country">Country:</label></li>
<li><select name="country">
<option selected="" value="Default">(Please
select a country)</option>
<option value="AF">Australia</option>
<option value="AL">Canada</option>
<option value="DZ">India</option>
<option value="AS">Russia</option>
<option value="AD">USA</option>
</select></li>
<li><label for="zip">ZIP Code:</label></li>
<li><input type="text" name="zip" /></li>
<li><label for="email">Email:</label></li>
<li><input type="text" name="email" size="50"
/></li>
<li><label id="gender">Gender:</label></li>
<li><input type="radio" name="m" value="Male"
></li>
<li><input type="radio" name="f" value="Female"
></li>
<li><label>Language:</label></li>
<li><input type="checkbox" name="en" value="en"
checked ><span>English</span></li>
<li><input type="checkbox" name="nonen"
value="noen" ><span>Non English</span></li>
<li><label for="desc">About:</label></li>
<li><textarea name="desc"
id="desc"></textarea></li>
<li><input type="submit" name="submit"
value="Submit" ></li>
</ul>
</form>
</body>
</html>
Javascript for form validation
function formValidation()
{
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var um = document.registration.m;
var uf = document.registration.f;
if(userid_validation(uid,5,12))
{
if(passid_validation(passid,7,12))
{
if(allLetter(uname))
{
if(alphanumeric(uadd))
{
if(countryselect(ucountry))
{
if(allnumeric(uzip))
{
if(ValidateEmail(uemail))
{
if(validgender(um,uf))
{
}
}
}
}
}
}
}
}
return false;
}
function userid_validation(uid,mx,my)
{
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be
between "+mx+" to "+my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid,mx,my)
{
var passid_len = passid.value.length;
if (passid_len == 0 ||passid_len >= my ||
passid_len < mx)
{
alert("Password should not be empty / length be
between "+mx+" to "+my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else {
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd)
{
var letters = /^[0-9a-zA-Z]+$/;
if(uadd.value.match(letters))
{
return true;
}
else
{
alert('User address must have alphanumeric characters
only');
uadd.focus();
return false;
}
}
function countryselect(ucountry)
{
if(ucountry.value == "Default")
{
alert('Select your country from the list');
ucountry.focus();
return false;
}
else
{
return true;
}
}
}
function allnumeric(uzip)
{
var numbers = /^[0-9]+$/;
if(uzip.value.match(numbers))
{
return true;
}
else
{
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\._]?\w+)*@\w+([\._]?\w+)*(\.\
w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
function validgender(um,uf)
{
x=0;

if(um.checked)
{
x++;
} if(uf.checked)
{
x++;
}
if(x==0)
{
alert('Select Male/Female');
um.focus();
return false;
}
else
{
alert('Form Succesfully Submitted');
return true;
}
OBJECTS

• Every web page resides inside a browser


window which can be considered as an object.
• A Document object represents the HTML
document that is displayed in that window.
• Window object − Top of the hierarchy. It is the
outmost element of the object hierarchy.
• Document object − Each HTML document that
gets loaded into a window becomes a
document object. The document contains the
contents of the page.
• Form object − Everything enclosed in the
<form>...</form> tags sets the form object.
• Form control elements − The form object
contains all the elements defined for that
object such as text fields, buttons, radio
buttons, and checkboxes.
Window
The window object can be used to create new
windows and dialog boxes and includes these
method:

• Open – Opens a new window


• Close – Closes the window
• alert – Displays an alert message box
• confirm – Displays a confirms dialog box
• prompt – Displays a prompt dialog box
Alert Message Box

alert('An Alert Message');


Confirm Dialog Box
document.write(confirm("Continue?"));
Prompt
• var result = prompt("Name:","");
document.write(result);
Document
• The Document object provides access to all of
the HTML elements of the current page.

• In addition, it consists of a series of array that


hold the contents of the page. These objects
can be accessed and modified. For example,
the forms array contains a list of all of the
forms that make up a page.
document.forms[0].elements[2].value

Here the first form is selected. The value of the


third element of the form is returned.
Introduction to AJAX
• AJAX is about updating parts of a web page,
without reloading the whole page.

• AJAX = Asynchronous JavaScript and XML.

• AJAX is a technique for creating fast and


dynamic web pages.
• AJAX allows web pages to be updated
asynchronously by exchanging small amounts
of data with the server behind the scenes. This
means that it is possible to update parts of a
web page, without reloading the whole page.

• Classic web pages, (which do not use AJAX)


must reload the entire page if the content
should change.

• Examples of applications using AJAX: Google


Maps, Gmail, Youtube, and Facebook.
The term Ajax is used to describe a set of
technologies that allow browsers to provide
users with a more natural browsing experience.
Before Ajax, Web sites forced their users into
the submit/wait/redisplay paradigm, where the
users' actions were always synchronized with
the server's "think time."
Ajax provides the ability to communicate with
the server asynchronously, thereby freeing
the user experience from the
request/response cycle.
AJAX Incorporates
• Standards-based presentation using HTML
and CSS

• Dynamic display and interaction using the


Document Object Model

• Asynchronous server communication using


XMLHttpRequest

• JavaScript binding everything together


With AJAX one can…
• Dynamically update the totals on your
shopping cart without forcing the user to click
Update and wait for the server to resend the
entire page.

• Increase site performance by reducing the


amount of data downloaded from the server.

• Eliminate page refreshes every time there is


user input..
Working of AJAX
1) A JavaScript creates an XMLHttpRequest
object, initializes it with relevant information as
necessary, and sends it to the server. The script
(or web page) can continue after sending it to the
server.

2) The server responds by sending the contents of a


file or the output of a server side program (written,
for example, in PHP).
3) When the response arrives from the server, a
JavaScript function is triggered to act on the data
supplied by the server.

4) This JavaScript response function typically


refreshes the display using the DOM, avoiding the
requirement to reload or refresh the entire page.
Advantages

• Your page will be more pleasant to use, when


you can update parts of it without a refresh,
which causes the browser to flicker and the
status bar to run.
• Because you only load the data you need to
update the page, instead of refreshing the
entire page, you save bandwidth.

You might also like