0% found this document useful (0 votes)
3 views29 pages

3 Understand XML and Client side scripting using Java Script

This document provides an overview of XML and client-side scripting using JavaScript. It covers XML structure, rules for designing XML documents, the significance of namespaces, and various applications of XML, along with a comparison between client-side and server-side scripting. Additionally, it details JavaScript features, function definitions, parameter passing, and form handling for client-side validation.

Uploaded by

23022cm050
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views29 pages

3 Understand XML and Client side scripting using Java Script

This document provides an overview of XML and client-side scripting using JavaScript. It covers XML structure, rules for designing XML documents, the significance of namespaces, and various applications of XML, along with a comparison between client-side and server-side scripting. Additionally, it details JavaScript features, function definitions, parameter passing, and form handling for client-side validation.

Uploaded by

23022cm050
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

COURSE HANDOUT

UNIT - 3
Understand XML and Client side scripting using Java Script

3.1 Understand XML


3.1.1 Describe how to organize data in the form of XML.

XMI- stands for extensible markup lanquage


XMI. is a markup language much like HTML
XML was designed to store and transport data
XML was designed to be self-descriptive
XML is a W3C Recommendation
Example for an XML file :
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Dont forget me this weekend!</body>
</note>
The above is an XML file which is quite self-descriptive. It has sender and receiver
information. It also has a heading and a message body. But still, this XML
document does not DO anything. XML is just information wrapped in tags.
Someone must write a piece of software to send, receive,store, or display it.

3.1.2 Explain the rules for designing XML document.

XML Documents must have a root element


The XML must have prolog
All XML elements must have a closing tag
XML tags are case sensitive
XML. elements must be properly nested
XML attribute values must be quoted
XML has entity references
Comments in XML
White-space is Preserved in XML
Example :
<? xml version="1.0" encoding="UTF-8 ?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

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.
&lt; < less than
&gt: < Greater than
Samp; & ampersand
&apos; @Postrophe
&quot; “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 -->

3.1.3 Understand the significance of Namespace

XML Namespaces provide a method to avoid element name conflicts.


The namespace can be defined by an xmlns attribute in the start tag of an
element.
Syntax:
xmlns:prefix= "URI".
Example :
<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="http://www.w3schools.com/furniture'>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
Or Namespaces can also be declared in the XML root element:
<root
Xmlns:h=”http://www.w3.org/TR/btml4/"
Xmlns:f=”hhttp //www.w3schools.com/furniture" >
<h: table >
<h:tr>
<h:td>Apples</h:td>
sh:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<fname>African Coffee Table</f:name>
<f:width>80</f-widths
<flength>120</f-length>
</f:table>
</root>

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>

The css file is cd_catalog.css


CATALOG {
background-color: # fff fff;
width: 100%;
}
CD {
Display : block:
Margin-bottom: 30pt
Margin-left:0:
}
TITLE {
Display: block.
Color: #ffO000.
font size: Z2Opt.
ARTIST |
Display: block:
color: #0000ff:
font-size: 2Opt:
|
COUNTRY. PRICE, YEAR, COMPANY {
display: block:
color: #000000;
margin-left: 20pt;
3.1.4 List the various applications of XML.

1. Configuration of files.
2. Media for data interchange.
3. Business-to-Business transaction on the web.

3.2 Types of scripting-JavaScript


3.2.1 Differentiate between Client-side and Server-side scripting.

Client-Side Environment: The client side environment used to run scripts it


usually a browser. The processing takes place on the end users computer.
The processing takes place on the end users computer. The source code
transferred from the web server to the user’s computer over the internet
and run directly in the browser.
The scripting language needs to be enabled on the client computer.
Sometimes if a user is conscious of security risks they may switch the
scripting facility off. When this is the case a message usually pops up to alert
the user when script is attempting to run.
Server-Side Environment: The server-side environment that runs a scripting
language is a web server. A user’s request is fulfilled by running a script
directly on the web server to generate dynamic HTML pages. This HTML is
then sent to the client browser. It is usually used to provide interactive web
sites that interface to databases or other data stores on the server.
This is different from client-side scripting where scripts are run by the
viewing web browser, usually in JavaScript. The primary advantage to
server-side scripting is the ability to highly customize the response based
on the user's requirements, access rights, or queries into data stores.
3.2.2 List Client side and server side scripting languages

Client side scripting languages

• Javascript
• JScript
• VBScript
• ActionScript
• Java applet

server side scripting languages

• PHP
• ASP.NET (C# OR Visual Basic)
• Java and JSP
• Python
• Ruby on Rails
• Javascript

3.2.3 Describe the features of Java Script.

• JavaScript is a lightweight, interpreted programming language.


• Designed for creating network-centric applications.
• Complementary to and integrated with Java.
• Complementary to and integrated with HTML.
• Open and cross-platform

3.2.4 Placing JavaScript code in HTML.

In HTML, JavaScript code is inserted between <script> and </script> tags.

Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

External Scripts

Scripts can also be placed in external files:

JavaScript files have the file extension .js.

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>

<h1>A Web Page</h1>


<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

3.2.5 Understand functions


3.2.5.1 Know how to define and call a function.

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

The basic syntax is shown here.


<script type = "text/javascript">

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>

3.2.5.1 Know how to pass parameters.

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>

Arguments are Passed by Value

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.

Changes to arguments are not visible (reflected) outside the function.


Objects are Passed by Reference

In JavaScript, object references are values. Because of this, objects will behave like they are passed
by reference:

If a function changes an object property, it changes the original value.

Changes to object properties are visible (reflected) outside the function.

The return Statement


A JavaScript function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement in a function.
For example, you can pass two numbers in a function and then you can expect the function to
return their multiplication in your calling program.

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>

3.2.5.3 Understand the purpose of GetElementBId method

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>

3.2.5.4 Describe the global functions provided by JavaScript.

JavaScript Global Properties


Property Description
Infinity A numeric value that represents positive/negative infinity
NaN "Not-a-Number" value
undefined Indicates that a variable has not been assigned a value

JavaScript Global Functions


Function Description
decodeURI() Decodes a URI
decodeURIComponent() Decodes a URI component
encodeURI() Encodes a URI
encodeURIComponent() Encodes a URI component
eval() Evaluates a string and executes it as if it was script code
isFinite() Determines whether a value is a finite, legal number
isNaN() Determines whether a value is an illegal number
Number() Converts an object's value to a number
parseFloat() Parses a string and returns a floating point number
parseInt() Parses a string and returns an integer
String() Converts an object's value to a string

3.2.6 Form Handling in Java Script


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 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 − First of all, the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop 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.

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>

Basic Form Validation


First let us see how to do a basic form validation. In the above form, we are calling validate() to
validate data when onsubmit event is occurring. The following code shows the implementation
of this validate() function.
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {

if( document.myForm.Name.value == "" ) {


alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
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;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>

Data Format Validation


we can validate our entered form data before submitting it to the web server.
The following example shows how to validate an entered email address. An email address must
contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of the email
address, and the last dot must at least be one character after the ‘@’ sign.

Example

Try the following code for email validation.


<script type = "text/javascript">
<!--
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");

if (atpos < 1 || ( dotpos - atpos < 2 )) {


alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
3.2.7 Illustrate Arrays
3.2.7.1 Understand single and multi-dimensional arrays.

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];

Creating a single dimensional Array

Syntax:

var array_name = [item1, item2, ...];

Ex:
var cars = ["Saab", "Volvo", "BMW"];

Using the JavaScript Keyword new

We can alos create an Array, and assigns values to it using new keyword

Example
var cars = new Array("Saab", "Volvo", "BMW");

Access the Elements of an Array


You access an array element by referring to the index number. Array indexes start with 0.

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>

Multi Dimensional Array: It is an array of arrays.


Ex: a =[
[3,7,9,11],
[2,4,6,8]
];

Creating Multi dimensional Array


Syntax:
var array_name = [
[row0 elements with commas],
[row 1 elements with commas],
:
[row n elements with commas],
];
Ex:
var a =[
[3,7,9,11],
[2,4,6,8]
];

Accessing Access the Elements


We can access individual elements with row index and column index.

A[0][0] refers 3 which first row and first column element


A[0][1] refers 7 which is first row and second column element

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

The length Property


The length property of an array returns the length of an array (the number of array
elements).

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.

3.2.7.1 Design small programs using arrays.

Write a program on insert and remove elements from array

<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

3.2.8 Understand about various Objects provided by JavaScript


3.2.8.1 Math object

The Math object allows you to perform mathematical tasks.

Math is not a constructor. All properties/methods of Math can be called by using Math as an object, without
creating it:

var x = Math.PI; // Returns PI


var y = Math.sqrt(16); // Returns the square root of 16

Math Object Properties


Property Description
E Returns Euler's number (approx. 2.718)
LN2 Returns the natural logarithm of 2 (approx. 0.693)
LN10 Returns the natural logarithm of 10 (approx. 2.302)
LOG2E Returns the base-2 logarithm of E (approx. 1.442)
LOG10E Returns the base-10 logarithm of E (approx. 0.434)
PI Returns PI (approx. 3.14)
SQRT1_2 Returns the square root of 1/2 (approx. 0.707)
SQRT2 Returns the square root of 2 (approx. 1.414)

Math Object Methods


Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians
cbrt(x) Returns the cubic root of x
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
cosh(x) Returns the hyperbolic cosine of x
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithmof x
max(x, y, z, ..., Returns the number with the highest value
n)
min(x, y, z, ..., Returns the number with the lowest value
n)
pow(x, y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sign(x) Returns the sign of a number (checks whether it is positive, negative or
zero)
sin(x) Returns the sine of x (x is in radians)
sinh(x) Returns the hyperbolic sine of x
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

3.2.8.2 String object

A JavaScript string stores a series of characters like "John Doe".

A string can be any text inside double or single quotes:

var carName1 = "Volvo XC60";


var carName2 = 'Volvo XC60';
String indexes are zero-based: The first character is in position 0, the second in 1, and so
on.

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

3.2.8.3 Date Object

The Date object is used to work with dates and times.

Date objects are created with new Date().


There are four ways of instantiating a date:

var d = new Date();


var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

Date Object Methods


Method Description
Date() Returnd today’s date and time
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
getTime() Returns the number of milliseconds since midnight Jan 1 1970,
and a specified date
getYear() Deprecated. Use the getFullYear() method instead
now() Returns the number of milliseconds since midnight Jan 1, 1970
parse() Parses a date string and returns the number of milliseconds since
January 1, 1970
setDate() Sets the day of the month of a date object
setFullYear() Sets the year of a date object
setHours() Sets the hour of a date object
setMilliseconds() Sets the milliseconds of a date object
setMinutes() Set the minutes of a date object
setMonth() Sets the month of a date object
setSeconds() Sets the seconds of a date object
setTime() Sets a date to a specified number of milliseconds after/before
January 1, 1970
setYear() Deprecated. Use the setFullYear() method instead
toDateString() Converts the date portion of a Date object into a readable string
toGMTString() Deprecated. Use the toUTCString() method instead
toISOString() Returns the date as a string, using the ISO standard
toJSON() Returns the date as a string, formatted as a JSON date
toLocaleDateString() Returns the date portion of a Date object as a string, using locale
conventions
toLocaleTimeString() Returns the time portion of a Date object as a string, using locale
conventions
toLocaleString() Converts a Date object to a string, using locale conventions
toString() Converts a Date object to a string
toTimeString() Converts the time portion of a Date object to a string
toUTCString() Converts a Date object to a string, according to universal time
3.2.8.4 Boolean and Number object

JavaScript Booleans

JavaScript booleans can have one of two values: true or false.

The Boolean() Function

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

JavaScript has only one type of number.

Numbers can be written with, or without, decimals:

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

3.2. 9 Describe events in java script.

Event

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

Here are some examples of HTML 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

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event=”some JavaScript”>

Ex: <button onclick="displayDate()">The time is?</button>

Some of the commonly used event handler attributes are


Mouse event attributes:
Attribute Description
onclick When mouse click on an element
onmouseover When the cursor of the mouse comes over the element
onmouseout When the cursor of the mouse leaves an element
onmousedown When the mouse button is pressed over the element
onmouseup When the mouse button is released over the element
onmousemove When the mouse movement takes place.

Keyboard event attributes:


Attribute Description
onkeydown When the user press key
onkeyup When the user release the key

Form event attributes:


Attribute Description
onfocus When the user focuses on an element
onsubmit When the user submits the form
onblur When the focus is away from a form element
onchange When the user modifies or changes the value of a form element

Window/Document event attributes:


Attribute Description
onload When the browser finishes the loading of the page
onunload When the visitor leaves the current webpage, the browser unloads it
onresize When the visitor resizes the window of the browser

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>

You might also like