Chapter 3: Client-Side Scripting Language
Chapter 3: Client-Side Scripting Language
3.1 Introduction
HTML is a markup language. It describes content and structure of your web page. It deals
with questions like - What is your head line? How many divisions are there in your page?
How many paragraphs you have? What are the contents of those paragraphs?etc.
CSS is a style sheet language for presentation. It deals with questions like - What font
does the head line use? What is the background color of the page?etc.
XML is an extensible markup language. It is used to store and transport data. It deals with
questions like How can I store my data in a database? How can I transport my data
from one machine to another? etc.
JavaScript is a programming language. It deals with questions like - What is the behavior
and interactivity of the web page? What happens when you mouse over a menu? What
happens when you type wrong value in a form field?etc.
Javascript works inside another application ie. your web browser. All web browsers have
javascript engine inside them. The operating system runs the web browser. The web
browser contains a page and the page contains javascript.
Javascript is designed to manipulate web pages. It runs inside a web page. It is a scripting
language. It cant access local files. It cant access database. It cant access hardware.
3.2 Client-Side Scripting Using JavaScript
3.3.2
Variables:
Variables use the following naming rules:
A variable may include only the letters a-z, A-Z, 0-9, the $ symbol, and the underscore (_).
No other characters such as spaces or punctuation are allowed in a variable name.
The first character of a variable name can be only a-z, A-Z, $, or _ . Variable names should not begin
with number.
Names are case-sensitive. Count, count, and COUNT are all different variables.
There is no set limit on variable name lengths.
Expressions:
Logical expressions contain <,>,==,===,>=,<=,&&, ||
Arithmatic expressions contain +,-,*,/
Control Structures
Selection Structures: if, if-else, if-elseif-elseif-...-else, switch.
Looping strutcures: for, while, do.
Arrays: Arrays in javascript are actually objects. They can contain heterogeneous elements.
2
<html>
<body>
<script>
cars=["BMW",34,"Saab",5.46,false];
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
</script>
</body>
</html>
3.3.3
<html>
<head>
<script>
function myFunction()
{ alert("Hello World!"); }
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
3
<html>
<body>
<h3>Click to change the content below</h3>
<p id="demo">
JavaScript can change the content of an HTML
element.
</p>
<script>
function myFunction()
{
x=document.getElementById("demo"); // Find the
element
x.innerHTML="Hello JavaScript!";
// Change the
content
}
</script>
<button
type="button"
onclick="myFunction()">Click Me!</button>
</body>
</html>
<html>
<body>
<p>Click the button </p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="",i=0;
for (i=0;i<10;i++)
{
if (i==3)
{
continue;
}
x=x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
<html>
<body>
<p>Click the button </p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{var x="",i=0;
for (i=0;i<10;i++)
{ if (i==3)
{ break; }
x=x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
Exception Handling
Exception handling is necessary, when you wish to continue the execution of code, even
if an error(exception) is encountered. This can be achieved by using try,catch and throw
statements.
The try statement lets you to test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom error messages
<html>
<head>
<script>
var txt="";
function message()
{
adddlert("Welcome guest!"); //Exception handling
not used addlert() not defined- so execution stops
here
document.write("something");// This statement
will not be printed
}
</script>
</head>
<body>
<input type="button" value="View message"
onclick="message()">
</body>
</html>
<html>
<head>
<script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
document.write("something");//This statement will
be executed even if addlert() is not defined.
}
</script>
</head>
<body>
<input type="button" value="View message"
onclick="message()">
</body>
</html>
3.3.4
<html>
<body>
<h3>Input validation using JavaScript</h3>
<p>Please input a number.</p>
<input id="demo" type="text">
<script>
function myFunction()
{
var x=document.getElementById("demo").value;
if(x==""||isNaN(x))
{
alert("Not Numeric");
}
}
</script>
<button
type="button"
onclick="myFunction()">Click Me!</button>
</body>
</html>
6
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["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>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["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>
3.3.5
A cookie is a variable that is stored on the visitor's computer. Each time the same
computer requests a page with a browser, it will send the cookie too.
<html>
<body onload="checkCookies()">
<script>
function checkCookies()
{
if (navigator.cookieEnabled==true)
{alert("Cookies are enabled") }
else
{alert("Cookies are not enabled")
}
}
</script>
<p>An alert box should tell you if your browser has
enabled cookies or not.</p>
</body>
</html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
</html>
Note:
The Cookie String
The document.cookie property looks like a normal text string. But it is not.
If you set a new cookie, older cookies are not overwritten. The new cookie is added to
document.cookie, so if you read document.cookie again you will get something like:
cookie1=value; cookie2=value;
If you want to find the value of one specified cookie, you must write a JavaScript function that
searches for the cookie value in the cookie string.
function getCookie(cname) explained below:
Take the cookiename as parameter (cname).
Create a variable (name) with the text to search for (cname + "=").
Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')).
Loop through the ca array (i=0;i<ca.length;i++), and read out each value c=ca[i]).
If the cookie is found (c.indexOf(name) == 0), return the value of the cookie
(c.substring(name.length,c.length).
If the cookie is not found, return "".
Hidden fields
The values of form elements including type='hidden' are submitted to the server when the form is
posted. input type="hidden" values are not visible in the page. Hidden fields are useful to send
user IDs to the server, so that any user data can be maintained uniquely.
<html>
<body>
<script >
function printIt(){
alert(document.getElementById('abcId').value);
alert(document.formName.elements['abcName'].value);
}
</script>
9
value="Get
Value"
</body>
</html>
***
10