Unit 4
Unit 4
The language attribute explicitly informs the browser that the enclosed code is JavaScript
•The type attribute specifies that the code is in text format
• ’document’ refers to the body of an HTML document defined by <body>...</body> tags
• ’write’ is a method used for writing output to a page
• The browser recognizes the lines between the <script>...</script> tags as JavaScript code and executes it
External Script file
Including script as an external file is helpful
– If you want to use the same script on several pages
– If the script code is complex
– If the code is likely to be revised often
– To protect (though partly!) precious code
Guidelines to create and use script files
– Save the external JavaScript file with a .js file extension
– The external file cannot contain the <script> tag!
– Use the "src" attribute of the <script> tag to include the script file
– Place the script exactly where you normally would write it
Example:
<head><script type="text/javascript" src=“myScript.js"> </script>
</head>
Syntax and Functions of Client Side Scripting
Topics to be covered
• Variables
• Arithmetic, Assignment, Relational and Logical operators
• Selection control structures
Variables
- Definition
- Rules for JavaScript Variable Names
- Variable Declaration
Variables
Variables are storage areas used to hold data values
• A variable's value can change during the execution of a script
• A variable must have a unique name
• You refer to a variable by its name to display or change its value.
After the declaration shown above, the variables are empty (they have no meaningful values yet).
You can also assign values to the variables when you declare them.
var a=5; //int value
var company=“Infosys"; //String value
Operators
• Arithmetic
• Assignment
• Logical
• Relational
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or constants.
Given that y=5, the table below explains the arithmetic operators
Syntax
if (condition)
{
// code to be executed if condition is true
}
• When JavaScript encounters an if statement, it checks the condition.
• If and only if, the condition is found to be true, the statements enclosed within the curly braces are
executed.
if else statement
Each condition has two paths from which we choose one.
For example, "If it's raining, I'll stay at home else I'll go out for a stroll.“
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}
Switch statement
Using the switch statement, we can select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is other than case 1
and 2
}
Functions of Client Side Scripting
Topics to be covered
• User defined functions (Definition,Syntax)
• Conversion Functions(parseInt,parseFloat,isNaN)
• alert(),prompt(),confirm() methods
• Local and Global Variables
• Events and Event Handlers
- JavaScript Events
(click, change, focus, load, mouseOver, mouseOut, select, blur)
- JavaScript Event Handlers
(onClick, onMouseOver, onMouseOut, onChange, onFocus, onBlur, onSelect)
Functions
A function is a block of code that performs a single, related action.
Functions can be of two types
- Built-in
- User-defined
Syntax of user-defined functions:
function fnName(parameterlist)
{
// body of function
}
User Defined functions
• A function consists of the function keyword, name of the function, parameters (if any) and JavaScript
statement/s
• Functions are placed in the head section of the HTML document. This ensures that a function is loaded by the
browser before it is called.
• Function calls can occur in any part of the document and even inside event handler code.
• A return statement is used to transfer control out of a function or to return a value.
User Defined Functions
<html>
<head> <title>Functions</title>
<script language="javascript" type="text/javascript">
<!--
function alert_box(msg)
{
document.bgColor="#EEEEEE";
alert(msg);
}
// -->
</script> </head>
<body>
<script language="javascript" type="text/javascript">
<!--
alert_box("Welcome to Goa");
// -->
</script> </body></html>
Conversion Functions
For parseInt()and parseFloat() to work correctly, the string must be composed entirely of digits.
parseInt() - Converts a string to an integer value
parseFloat() - Converts a string to a floating point number
•When parseInt()or parseFloat()encounters an alphabet or any non-digit character, parsing (conversion) stops
and the function returns NaN,which means Not a Number.
•This can be tested using isNaN() function
var n = prompt("Check your number", "");
n = parseInt(n);
if (isNaN(n))
{
alert("The input cannot be parsed to a number");
}
alert(),prompt(),confirm()
These are methods of the window object
•Used to interact with the user
•When executed, each method displays a message box having a specific purpose
•The methods take a string (say messageText) as parameter
•messageText must be a valid JavaScript string
alert()
Syntax:
alert(messageText);
•Displays a message box with messageText as the message
Example:
alert(“This is an alert Box");
•Useful in
– Making outputs
– Debugging JavaScript code
confirm()
Syntax:
confirm(messageText);
• Displays a message box with “messageText” as the message and an "OK" and a "Cancel" button
Example:
confirm ("Do you wish to continue?");
• When the user clicks on "OK" the value 'true' is returned, while clicking on "Cancel" returns 'false’
• We can capture this returned value in a variable and test it through an if statement
prompt()
Syntax:
prompt(messageText, response);
•In addition to the message and "OK" and "Cancel" buttons, a prompt box also has a text field for gathering user input
•JavaScript lets you specify a default text for the text field through the response parameter. The response parameter is optional.
•Example:
prompt ("Enter day: ", "Tuesday"); // default response –"Tuesday"
prompt ("Enter day: ", ""); // for empty textbox
Response submitted by the user can be stored in a variable
•This value will always be of string data type
•If you want to receive numeric data through prompt(), JavaScript provides two functions to convert string value to a numeric value
–parseInt()
•Converts a string to an integer value
–parseFloat()
•Converts a string to a floating point number
Local and Global Variables
Variables created inside a function are called Local variables. They have no
presence outside the function.
- Values of local variables cannot be changed by the main code or other functions.
- Variables that are created outside any function are called Global variables.
- Their values are available anywhere in the code and to all functions
Events and Event Handlers
Event is an action that occurs when a user interacts with a Web page such as
–Moving the mouse over text
–Clicking a button
To make interactive pages you need to catch or recognize the events.
Event handler is a subroutine associated with an HTML element to capture an event.
An event handler calls a JavaScript function in response to an event.
JavaScript Events
Event Description
click Generated when a user clicks on a form element or on a link
change Generated when a user changes the value of a form field
focus Generated when a user gives input to a form element
load Generated when a page is loaded into the browser
mouseOver Generated when a user moves the mouse pointer over a link or area object
mouseOut Generated when the mouse pointer leaves the link or area object
select Generated when a user selects a form field
blur Generated when the input focus is removed from a form
JavaScript Event Handlers
Object Event Handler
Button onClick
Reset onClick
Submit onClick
Radio onClick
CheckBox onClick
Link onClick, onMouseOver and onMouseOut
Form onSubmit and onReset
Text onChange, onFocus, onBlur and onSelect
TextArea onChange, onFocus, onBlur and onSelect
Select onChange, onFocus and onBlur
Image onAbort and onError
Area onClick, onMouseOver and onMouseOut
Window onLoad, onUnLoad and onError
JavaScript Loops
Loops are used to execute blocks of code repeatedly
There are three types of looping constructs:
a) for loop
b) while loop
c) do...while loop
for Loop
Syntax
for (Initialization; Condition; Update statements)
{
... body of loop ...
}
Steps in loop execution
– When the JavaScript interpreter comes across a for loop, it executes the initialization statements and then checks the
condition.
– Only if the condition returns 'true', the interpreter enters the loop.
– After each iteration, the update statements are executed and the condition is evaluated again.
– The loop stops when the condition returns 'false'.
while Loop
Syntax
while (condition)
{
...statements...
…including update statement…
}
- As long as the condition evaluates to 'true', the program execution will continue to loop through the
statements.
- If the condition in while evaluates to 'false' at the beginning itself, the loop is skipped altogether and program
execution starts at the statement immediately following the loop.
do while Loop
Syntax
do
{
...statements...
…including update statement…
} while (condition);
As long as the condition evaluates to 'true', the program execution will continue to loop through the
statements.
Here, the condition is placed at the end of the loop and hence, the loop is executed at least once.
Document Object Model
Topics to be covered
• DOM Hierarchy
• Accessing elements in a DOM tree
• DOM Identifiers and Methods
Document Object Model
The DOM gives you scripting access to all the elements on a web page. Inside the browser, the whole web page
—paragraphs, forms, tables, etc.—is represented in an object hierarchy. Using JavaScript, you can dynamically
create, modify and remove elements in the page.
Document Object Model
A hierarchy demonstrates the principle of containership
•Lower-level objects are contained within top-level objects
•In order to reference a lower-level object, we also need to reference its parent or container object
•JavaScript uses the dot (.) to separate the parent object from its components
In DOM, documents have a logical structure which is very much like a tree; to be more precise, which
is like a "forest" or "grove", which can contain more than one tree. Each document contains zero or one
doctype nodes, one root element node, and zero or more comments or processing instructions; the root
element serves as the root of the element tree for the document. However, the DOM does not specify that
documents must be implemented as a tree or a grove, nor does it specify how the relationships among
objects be implemented.
Finding HTML Elements
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
Changing HTML Elements
Property Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element
Adding and Deleting HTML elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream
Adding Event Handlers
Method Description
document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event
Sample Codes
How to use getElementById()
<html>
<head>
<title>Introduction to Objects</title>
<script type="text/javascript">
//DOM Manipulation and getElementById Method//
function buttonClick()
{
document.getElementById("heading2").innerHTML=“This is new text ";
}
</script>
</head>
<body>
<button onclick="buttonClick()">Click me</button>
<h2 id="heading2">Some Random Text</h2>
</body>
</html>
How to use getElementsByClassName()
<html>
<head>
<script type="text/javascript">
function styleChange()
para[i].style.fontSize = 24;
para[i].style.fontWeight = "bold";
para[i].style.fontStyle = "italic";
</script>
</head>
</body>
</html>
How to use getElementByTagName
<html>
<head>
<title>DOMS using JS</title>
<script type="text/javascript">
function styleChange()
{
var para = document.getElementsByTagName("p");
for(var i = 0; i < para.length; i++)
{
para[i].style.fontSize = 24;
para[i].style.fontWeight = "bold";
para[i].style.fontStyle = "italic";
}
}
</script>
How to use getElementByTagName
</head>
<body bgcolor = "black">
<p style = "color:tomato">#1 Paragraph</p>
<p style = "color:tomato">#2 Paragraph</p>
<p style = "color:tomato">#3 Paragraph</p>
<p style = "color:tomato">#4 Paragraph</p>
<p style = "color:tomato">#5 Paragraph</p>
<button onclick = "styleChange()" name = "Submit">Change Style</button>
</body>
</html>
Creating Form Elements using DOM
<html>
<head>
<title>DOMS using JS</title>
<script type="text/javascript">
function create()
{
mdiv = document.getElementById("a");
sel = document.createElement("Select");
op1 = document.createElement("Option");
op2 = document.createElement("Option");
op3 = document.createElement("Option");
tn1 = document.createTextNode(“Suzuki");
tn2 = document.createTextNode(“Toyota");
tn3 = document.createTextNode(“Hyundai");
Creating Form Elements using DOM
op1.appendChild(tn1);
op2.appendChild(tn2);
op3.appendChild(tn3);
sel.appendChild(op1);
sel.appendChild(op2);
sel.appendChild(op3);
mdiv.appendChild(sel);
}
</script>
</head>
<body bgcolor = "black">
<input type="button" value="Click" onclick="create();">
<br><br>
<div id = "a"> </div>
</body>
</html>
Validation
- Required Field Validator
- Check Number Validation
- Email Validation
- Checkbox and Radio Button Validation
- Drop Down list Validation
JavaScript Form Validation
JavaScript can be used to validate data in
HTML forms before sending off the content to
a server.
• Form data that typically are checked by a
JavaScript could be:
1. has the user left required fields empty?
2. has the user entered a valid e-mail address?
3. has the user entered a valid date?
4. has the user entered text in a numeric field?
Required Field Validator
The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false
and the form will not be submitted:
<html>
<head>
<script>
function validateForm()
{
var x=document.myForm.fname.value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.php" onsubmit="return validateForm()“ method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
E-mail Validation
The function below checks if the content has the general syntax of an email.
1. This means that the input data must contain an @ sign and at least one dot (.)
eg: [email protected] ; [email protected]
2. the @ must not be the first character of the email address
3. the last dot must be present after the @ sign
4. minimum 2 characters before the end
E-mail Validation
<html>
<head><script>
function validateForm()
{
var x=document.myForm.email.value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script></head>
<body>
<form name="myForm" action="demo_form.php" onsubmit="return validateForm();"
method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body></html>
Check Number
if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format ######" );
document.myForm.Zip.focus() ;
return false;
}
Code in <body>
<select name="Country">
<option value="-1" selected>Select country</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
Checkbox & Radio button
If(document.myForm.mycheckbox.checked == false)
{
alert(“Please select a value");
return false;
}
Question Bank
1) Write a note on the DOM Hierarchy.
2) What are Events and Event Handlers?
3) Name any 2 Validations and write a JavaScript function for the same .
4) List 3 rules to be followed while naming a JavaScript Variable.
5) Write a note on Client Side Scripting.
6) Differentiate between Java and JavaScript?
7) Name any 3 DOM identifiers and write a JavaScript function for the same .
8) List any 4 Applications of JavaScript.
9) What are local and global variables?
10) Name 2 conversion functions and explain in brief.
11) Explain in brief a) prompt() b) confirm()
12) List 4 Client Side Processes.