3 Understand XML and Client side scripting using Java Script
3 Understand XML and Client side scripting using Java Script
UNIT - 3
Understand XML and Client side scripting using Java Script
Explanation :
In the above example the line <? xml version='1.0° encoding="UTF-8"?> is called
as XML prolog. The XML prolog is optional. If it exists, it must come first in the
document.
Root : XML documents must contain one root element that is the parent of all
other elements. in the above example the tag <note> is root element.
In XML. it is illegal to omit the closing tag. All elements must
have a closing tag.
For example :
<p>This is a paragraph.
<br>
The above two are illegal. They must have Closing tags
<p>This Is 4 paragraph. </p>
<br >
XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
In XML, all elements must be properly nested within each other:
<b><i>This text is bold and italic</i></b>
Properly nested" simply means that since the <i> element is opened inside the
<b> element, it must be closed inside the <b> element.
In XML, the attribute values must always be quoted.
INCORRECT :
<note date=12/11/2007>
<to>Tove</to>
<from>Jani</from>
</note>
CORRECT :
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
Entity references are Special characters which have special meaning in XML. The
following are some of the special characters in XML.
< < less than
>: < Greater than
Samp; & ampersand
' @Postrophe
" “quotation mark
The syntax for waiting comments in XML is similar to that of HTML.
<!-- This is a comment -- >
Two dashes in the middle of a comment are not allowed.
Not allowed :
<!-- This is a -- comment -->
Displaying XML
Most browsers wil] display an XML document with color-coded elements.
For example as given below.
<?xml version="1.0" encoding="UTF-8"?>
- <note>
<to>Tove</tos
<from>Jani</froms
<heading>Reminder</heading>
<body>Don't forget me this weekend! </body>
</note>
To display output of an XML file CSS file should be used for example as qiven
below.
<?xml version="] ()" encoding="UTF-8"25
<? xml stylesheet type “text/ess” href "ed catalog. css"? >
<CATALOG >
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
1. Configuration of files.
2. Media for data interchange.
3. Business-to-Business transaction on the web.
• Javascript
• JScript
• VBScript
• ActionScript
• Java applet
• PHP
• ASP.NET (C# OR Visual Basic)
• Java and JSP
• Python
• Ruby on Rails
• Javascript
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
External Scripts
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:
Example
<script src="myScript.js"></script>
Example Progrm
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
</body>
</html>
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small
and manageable functions.
Function Definition
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
function functionname(parameter-list) {
statements
}
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters −
<script type = "text/javascript">
function sayHello() {
alert("Hello there");
}
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of
that function as shown in the following code.
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Function Parameters
We can pass different parameters while calling a function. These passed parameters can be
captured inside the function and any manipulation can be done over those parameters. A
function can take multiple parameters separated by comma.
Example
In the following example. sayHello function here. Now it takes two parameters.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say
Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
JavaScript arguments are passed by value: The function only gets to know the values, not the argument's
locations.
If a function changes an argument's value, it does not change the parameter's original value.
In JavaScript, object references are values. Because of this, objects will behave like they are passed
by reference:
Example
Try the following example. It defines a function that takes two parameters and concatenates
them before returning the resultant in the calling program.
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full;
full = first + last;
return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call
Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
The getElementById() is a DOM method used to return the element that has the ID attribute
with the specified value. This method returns null if no elements with the specified ID exists.
The ID should be unique within a page. However, if more than one element with the specified ID
exists, it returns the last element in the javascript code.
Syntax
document.getElementById(elementID)
Example Program
< html>
<body>
<p id="element">GetElementById</p>
<script>
document.getElementById("element").innerHTML = "Welcome";
</script>
</body>
</html>
Example
We will take an example to understand the process of validation. Here is a simple form in html
format.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit =
"return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Example
JavaScript arrays are used to store multiple values in a single variable. The values
of array can be accessed by referring an index number.
Arrays 2 types
Single Dimensional Array
Multi Dimensional Array
Single Dimensional Array: used to store a list of values with single column and
many rows
Ex: ages = [10,23,55,19];
Syntax:
Ex:
var cars = ["Saab", "Volvo", "BMW"];
We can alos create an Array, and assigns values to it using new keyword
Example
var cars = new Array("Saab", "Volvo", "BMW");
Ex:
var name = cars[0];
or
cars[0]= "Opel";
<html>
<head>
<title>JavaScript Single Dimensional Arrays</title>
</head>
<body>
<script>
var cars = ["Saab", "Volvo", "BMW"];
for(i=0;i<cars.length;i++)
{
document.write(cars[i]+”<br/>”);
}
</script>
</body>
</html>
Ex:
var t = a[0][0]
a[1][3] = 12;
<html>
<head>
<title>JavaScript Multi Dimensional Arrays</title>
</head>
<body>
<script>
var ages = [[23,14,46],[34,65,52],[12,27,36]];
for(var i=0;i<ages.length;i++)
{
for(var j=0;j<ages[i].length;j++)
{
document.write(ages[i][j]+”,”);
}
Document.write(“<br/>”);
}
</script>
</body>
</html>
Javascript Properties
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4
Array methods
Method Description
concat() Returns a new array comprised of this array joined with other array(s) and/or
value(s).
forEach() Calls a function for each element in the array.
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.
shift() Removes the first element from an array and returns that element.
unshift() Adds one or more elements to the front of an array and returns the new length of
the array.
slice()
Extracts a section of an array and returns a new array.
splice() Adds and/or removes elements from an array.
join() Joins all elements of an array into a string.
reverse() Reverses the order of the elements of an array -- the first becomes the last, and
the last becomes the first.
sort() Sorts the elements of an array
toString() Returns a string representing the array and its elements.
<html>
<head>
<title>JavaScript Array push Method</title>
</head>
<body>
<script type = "text/javascript">
var numbers = [1, 4, 9];
document.write(“Array is “ + numbers);
var length = numbers.push(10);
document.write("Array after adding 10 is: " + numbers );
var r = numbers.pop();
document.write("<br />Arrray after removing : " + r + “is :” +
numbers );
</script>
</body>
</html>
Output:
Array is : 1,4,9
Array after adding 10 is: 1,4,9,10
Arrray after removing : 10 is :1,4,9
Write a javascript program to sort array in ascending order and descending order
<html>
<head>
<title>JavaScript Array Sorting</title>
</head>
<body>
<script type = "text/javascript">
var arr = ["mango","pine apple","grapes","apple"];
document.write("Array is : " + arr );
var sorted_array = arr.sort()
document.write("<br/>Ascending ordered array is : " + sorted_array );
var sorted_array = arr.reverse()
document.write("<br/>Reversed array is : " + sorted_array );
</script>
</body>
</html>
Output
Array is : mango,pine apple,grapes,apple
Ascending ordered array is : apple,grapes,mango,pine apple
Reversed array is : pine apple,mango,grapes,apple
Math is not a constructor. All properties/methods of Math can be called by using Math as an object, without
creating it:
String Properties
Property Description
length Returns the length of a string
String Methods
Method Description
charAt() Returns the character at the specified index (position)
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a new joined strings
Returns the position of the first found occurrence of a specified
indexOf()
value in a string
Searches a string for a match against a regular expression, and
match()
returns the matches
Returns a new string with a specified number of copies of an
repeat()
existing string
Searches a string for a specified value, or a regular expression, and
replace()
returns a new string where the specified values are replaced
Searches a string for a specified value, or regular expression, and
search()
returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
startsWith() Checks whether a string begins with specified characters
Extracts the characters from a string, beginning at a specified start
substr()
position, and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object
JavaScript Booleans
You can use the Boolean() function to find out if an expression is true:
Example
Boolean(10 > 9) // returns true
Method Description
toString() Converts a boolean value to a string, and returns the result
valueOf() Returns the primitive value of a boolean
JavaScript Numbers
Example
var x = 3.14; // A number with decimals
var y = 34; // A number without decimals
Number Properties
Property Description
constructor Returns the function that created JavaScript's Number prototype
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a "Not-a-Number" value
POSITIVE_INFINITY Represents infinity (returned on overflow)
prototype Allows you to add properties and methods to an object
Number Methods
Method Description
isFinite() Checks whether a value is a finite number
isInteger() Checks whether a value is an integer
isNaN() Checks whether a value is Number.NaN
isSafeInteger() Checks whether a value is a safe integer
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point
toLocaleString() Converts a number into a string, based on the locale settings
toPrecision(x) Formats a number to x length
toString() Converts a number to a string
valueOf() Returns the primitive value of a number
Event
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
• Load event raise when An HTML web page has finished loading
• Change event raises An HTML input field was changed
• Click event raises when An HTML button was clicked
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
Example Program
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
function clickevent()
{
document.write("Clicked on Button");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Click me"/>
</form>
</body>
</html>