You are on page 1of 276

DOM

Vizu.chowdary@gmail.com JSCRIPT - 1
What CSS does?
Looks and formatting the document written in the mark-up language.(it impacts the document)
How the CSS know the para is located at somewhere? So there should be a mean by which the CSS should traverse to
the para.
So CSS should have an access to dig in to this para <p>

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 2
CSS it is working on the document elements (or) it is traversing to the DOM.
CSS will impact on para <p>

HTML

HEAD BODY

It can Para / list / etc.,

Whatever html document that we are specifying, somewhere its model has been defined and gets loaded.

HOW HTML PAGE LOAD TO BROWSER:


HTML page loading process:
1) We create HTML Markup, and we run index.html file on browser.
2) The browser retrieves and load HTML page, parsing its content from top to bottom.
3) The browser also builds and internal model of the HTML page, called the DOM.

On this DOM, css works on.

WHAT IS DOM (DOCUMENT OBJECT MODEL)?


DOM represents web page in tree structure.
DOM structure starts with Document and then

DOM STARTSDOCUMENT

HTML

HEAD BODY

It can be Para / list / etc.,

CSS checks, the role of the css is to dig into the DOM and whatever task has been asked to css loads.
DOM is created at BROWSER level.

Vizu.chowdary@gmail.com JSCRIPT - 3
Basic object of DOM:
- Screen (which provides height, width to us)
- Window (e.g., alert)
- Document: The web page displayed in the browser window is represented by the document object.

SCREEN IS HEIGHT AND WIDTH OF IT.

----------------------------------------------------------WIDTH----------------------------------------------------------
--------------------------------------HEIGHT--------------------------------------------------

This is called as WINDOW (whole complete browser)

The DOCUMENT starts the inner part of the browser

Vizu.chowdary@gmail.com JSCRIPT - 4
IN OUR PROGRAM CAN WE SEE THE DOM?
Yes, it’s possible. Using Mozilla Fire fox.
If you don’t have FIREBUG add-on in fire fox. Install it.

Press F12

Click on DOM

Vizu.chowdary@gmail.com JSCRIPT - 5
WINDOW (WITH THIS WE HAVE SO MANY OBJECTS, MAINLY WE WILL BE CONSIDERING SCREEN)

We can see the document here (expand this, we can find lot of objects)

Vizu.chowdary@gmail.com JSCRIPT - 6
Here we are looking something called as CHILDREN (EXPAND THIS)

Vizu.chowdary@gmail.com JSCRIPT - 7
Only one CHILDREN is available (expand this)

Vizu.chowdary@gmail.com JSCRIPT - 8
First Child is head
I am not looking for this. I am looking for CHILDREN.
Click here on HTML COLLECTION

Vizu.chowdary@gmail.com JSCRIPT - 9
Here we can see
WINDOW (we can click on this)
Within Window we went to DOCUMENT (we can click on this)
Within Document we went to CHILDREN (we can click on this)
0 CHILDREN (WITH IN THIS CHILDREN) (we can click on this)

Here we can see Head and the body

Let’s go inside the body. Click on body

Vizu.chowdary@gmail.com JSCRIPT - 10
So it is going to the 1st CHILDREN

Expand the CHILDREN

Here we can find P and OL

This is how we can determine DOM in Mozilla.


In Google Chrome we cannot see this DOM structure in this pattern.

Whenever HTML page gets loaded, DOM objects get created at browser level.
Browser is also an application. Browser is also a software. It has its own task.

Vizu.chowdary@gmail.com JSCRIPT - 11
DOM TREE:
- Each HTML element in a web page becomes a node in the DOM tree.
- HTML tags are known as elements and the actual content between the start tag and end tag are known as a text
node.
- The superordinate element are known as parent objects.

E.g.
<li> parent node is <ol>
<ol> parent node is <body>
- Subordinate element are known as children.
- Elements of the same rank are known as siblings

How to Address the DOM tree?


DOM Tree – Addressing Elements
Note: DOM tree structure is common for all browsers.
Why we need to address? What is the purpose?
Addressing makes us to interact with elements (makes web page interactive)

DOM PROPERTIES OF AN ELEMENT

In built PROPERTY DESCRIPTION


Firstchild First child node
childNodes[] Child Node [array]
Lastchild Last child node
nextSibling Next node at the same level
previousSibling Previous node at same level
parentNode ParentNodeS

Vizu.chowdary@gmail.com JSCRIPT - 12
DOM TREE

Vizu.chowdary@gmail.com JSCRIPT - 13
INBUILT METHODS

document.getElementById()
This will be used extensively by us.

As we have discussed in CSS,


Here we have single para. If we have multiple para.
In need to identify a particular element, which can be done by ID. For each of element I need to have an ID.

I can traverse directly using a method called document.getElementById()

Just jump to that.


Or
I need to travel first child, next child and last child (in that pattern)

One of the facility to address an element by using document.getElementById()

Vizu.chowdary@gmail.com JSCRIPT - 14
Another way is
getElementByTagName()
Whatever tag name we provided like para <p>, <body>
E.G.
37-38-15

DOM MANIPULATION:
You cannot only access the DOM in ready-only mode, but also change properties, move existing objects, add new
objects, and even delete objects.
- InnerHTML (to add, modify content): this is like text node.
Adding Elements
- appendChild();
- cloneNode();
- removeChild();

Why we are discussing this DOM?


Java script is scripting programming language, it does operations (decisions) and HTML is just which displays.

Java Script
HTML
Java Script is more on Mathematical operations
Meant for
designing Contains / more into PROGRAMMING DECISION

Java script is connected to HTML is through DOM


DOM is

Vizu.chowdary@gmail.com JSCRIPT - 15
JAVASCRIPT VS DOM MANIPULATION

Highest element in the DOM is WINDOW.

OUTPUT:

Click on this

I can write the JAVASCRIPT at element level.


But according to standard, it is said to be followed with <head> ………….. </head> tags.

Vizu.chowdary@gmail.com JSCRIPT - 16
Vizu.chowdary@gmail.com JSCRIPT - 17
DEBUG THE MISTAKE IN JAVASCRIPT

Trace it from the browser


Press F12.

Vizu.chowdary@gmail.com JSCRIPT - 18
I can see 1 error.

It is located at file name index.html: 10 (10 is line number). Click on it

After clicking, it is pointing to

Vizu.chowdary@gmail.com JSCRIPT - 19
Blink yellow color once and disappear.

Java script is CASE SENSITIVE. So correct it as document.write(‘ -----------------‘);

Now to refresh page click on CLEAR CONSOLE LOG.

Vizu.chowdary@gmail.com JSCRIPT - 20
Try to download (like fire bug)
Developer tools for Google chrome.

Click and install


==================================================================================================
Click on this

==================================================================================================

Click on ADD

Vizu.chowdary@gmail.com JSCRIPT - 21
DIFFERENCE BETWEEN SCRIPTING & LANGUAGES?

SCRIPTING LANGUAGES
1) LIGHT WEIGHT PROGRAMMING. 1) HEAVY WEIGHT PROGRAMMING.
E.G. E.G.
A) DOCUMENT.WRITE("BVK"); <- JAVA SCRIPT INCLUDE <STUDIO.H>
B) ECHO "BVK" <------------------------- SHELL MAIN( )
C) MSGBOX ("BVK") <--------------- IN VB SCRIPT {
D) PRINT("WELCOME"); <---------------- PERL }
2) EASY TO UNDERSTAND 2) COMPLEX TO UNDERSTAND
3) EASY TO IMPLEMENT 3) TROUBLE TO IMPLEMENT.
4) NO HEADER FILES REQUIRED 4) HEADER FILES ARE MANDATORY
5) NO SPECIAL LIBRARIES 5) REQUIRED SPECIAL LIBRARIES
6) NO SPECIAL COMPILERS 6) EVERY LANGUAGE, THEY REQUIRE THEIR OWN COMPILERS
7) MAXIMUM INTERPRETER BASED 7) MAXIMUM COMPILER BASED.
8) MOST TYPED PROGRAMMING (GLOBAL VARIABLE 8) STRICTLY TYPED PROGRAMMING (VARIABLE DECLARATION
DECLARATION) REQUIRED SEMICOLON, COMMA, QUOTATION MANDATORY)
9) CLIENT-SIDE VALIDATAION PURPOSE 9) VERIFICATION & VALIDATION BOTH.
10) POOR IN GRAPHICS IMPLEMNETATION 10) RICH IN GRAPHICS IMPLEMENTATION.
E.G. JAVA SCRIPT, VB SCRIPT, PERL SCRIPT ETC., E.G. C, C++, JAVA, COBOL, FORTRAN.

Vizu.chowdary@gmail.com JSCRIPT - 22
INTRODUCTION TO JAVA SCRIPT?
 TO MAKE HTML DYNAMIC WE USE JAVASCRIPT PROGRAMMING.
 THERE IS NO RELATIONSHIP BETWEEN JAVA & JAVASCRIPT, THEY ARE STANDALONE PROGRAMMING
LANGUAGES.
 JAVASCRIPT IS NOT EXECUTABLE FILE AS HTML, IT SHOULD BE INCLUDED IN HTML FILE. (AS CSS)
 IT IS FIRST WEB SCRIPTING LANGUAGE. IT IS CLIENT SIDE SCRIPTING LANGUAGE DEVELOPED BY "BRENDAN
RICH" IN NETSCAPE CORPORATION AT 1995. IT IS SUPPORTING ALL MAJOR MODERN BROWSERS LIKE GOOGLE
CHROME, MOZILLA FIREFOX, OPERA, SAFARI, I.E,
 NETSCAPE CORPORATION CAME OUT WITH A CLIENT SIDE SCRIPTING I.E. KNOWN AS LIVESCRIPT. IT IS THE FIRST
WEBSCRIPTING LANGUAGE.
 MICROSOFT CORPORATION JAVASCRIPT VERSION IS JSCRIPT. IT WAS FIRST INTRODUCED WITH I.E. VERSION 3.
(IT IS INITIALLY LIVESCRIPT. LATER RENAMED AS JAVASCRIPT).

NATURE OF JAVASCRIPT?
 IT IS OBJECT BASED PROGRAMMING LANGUAGE.
 IT IS BASED ON OBJECT ORIENTED PROGRAMMING CONCEPT.
 ITS SYNTAX IS SIMILAR TO C, C++ AND JAVA. IT IS EASY & SIMPLE TO IMPLEMENT.

WHY DO WE NEED JAVA SCRIPT?


 Make web page dynamic.
 Talk to the back-end server and build dynamic contents.
 With the help of Javascript, we can hit the DB as well. We can hit Application Server as well.
 To handle the Events.
 Validation.
 To make HTML dynamic we use JavaScript programming.

IS THERE ANY RELATIONSHIP BETWEEN JAVA AND JAVASCRIPT?


 There is no relationship between Java & JavaScript, they are stand-alone programming languages (i.e, it is not
dependent or any programming language).
 Java guys has taken this JavaScript. So it’s called as Javascript.
 They want to use JavaScript at client side and server side they want use java. In similar fashion we use Javascript
at front-end and use ABAP at back-end.
 Browser understands only JavaScript, not with java, .net and ABAP.

Important Points:
Java Script is CASE SENSITIVE.

Vizu.chowdary@gmail.com JSCRIPT - 23
WHAT IS JAVASCRIPT?
JAVA SCRIPT IS SATISFYING THE FOLLOWING LIST OF POINTS.
 IT IS USED TO VALIDATE DATA.
 IT IS USED TO CREATE COOKIES
1) IT IS BASICALLY LIVESCRIPT.
2) IT IS PURE CLIENT-SIDE PROGRAMMING TOOL.
3) IT CAN INTEGRATE WITH HTML TAGS.
4) IT IS LIGHTWEIGHT SCRIPTING.
5) IT IS INTERPRETED PROGRAMMING.
6) IT IS DESINERS PROGRAMMING TOOL.
7) IT CAN REACT TO EVENTS.
8) IT CAN READ & WRITE HTML ELEMENTS.
9) IT CAN INTEGRATE WITH ANY SERVER-SIDE PROGRAMMING.
10) OPEN SOURCE AND CROSS PLATFORM.
11) IT CREATES & READ THE EVENTS.
12) JAVASCRIPT CAN INTEGRATE WITH HTML & CSS CALLED DHTML.

CLIENT-SIDE JAVASCRIPT:

 The JavaScript code is executed when the user submits the form, and only if all the entries are valid they would
be submitted to the Web Server.
 JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that
the user explicitly or implicitly initiates.

ADVANTAGES OF JAVASCRIPT:

The merits of using JavaScript are:


 Less server interaction: You can validate user input before sending the page off to the server. This saves server
traffic, which means less load on your server.
 Immediate feedback to the visitors: They don't have to wait for a page reload to see if they have forgotten to
enter something.
 Increased interactivity: You can create interfaces that react when the user hovers over them with a mouse or
activates them via the keyboard. (HOVER – )
 Richer interfaces: You can use JavaScript to include such items as drag-and-drop components and sliders to give
a Rich Interface to your site visitors.

LIMITATIONS WITH JAVASCRIPT:

We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features:
 Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
 JavaScript cannot be used for networking applications because there is no such support available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into
otherwise static HTML pages.

Vizu.chowdary@gmail.com JSCRIPT - 24
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>......................</SCRIPT>

The script tag takes two important attributes:


 language: This attribute specifies what scripting language you are using. Typically, its value will
be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of
this attribute.
 type: This attribute is what is now recommended to indicate the scripting language in use and its value
should be set to "text/javascript".

So your JavaScript segment will look like:


<script language="javascript" type="text/javascript">
JavaScript code
</script>

Your First JavaScript Script:


Let us write our class example to print out "Hello World".

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
We added an optional HTML comment that surrounds our Javascript code. This is to save our code from a browser that
does not support Javascript. The comment ends with a "//-->". Here "//" signifies a comment in Javascript, so we add
that to prevent a browser from reading the end of the HTML comment in as a piece of Javascript code.

Next, we call a function document.write which writes a string into our HTML document. This function can be used to
write text, HTML, or both. So above code will display following result:

WHITE SPACES & LINE BREAKS:


 JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
 Because you can use spaces, tabs, and newlines freely in your program so you are free to format and indent your
programs in a neat and consistent way that makes the code easy to read and understand.
 Javascript ignores spaces, tabs & newlines that appear in Java Script. Using this white spaces & line breaks make
your script more readable.

Vizu.chowdary@gmail.com JSCRIPT - 25
Semicolons are Optional:
Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java.
JavaScript, however, allows you to omit this semicolon if your statements are each placed on a separate line. For
example, the following code could be written without semicolons
<script language="javascript" type="text/javascript">

<!--
var1 = 10
var2 = 20
//-->
</script>

But when formatted in a single line as follows, the semicolons are required:

<script language="javascript" type="text/javascript">


<!--
var1 = 10; var2 = 20;
//-->
</script>

Note: It is a good programming practice to use semicolons.

JAVASCRIPT IS CASE SENSITIVE:

JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other
identifiers must always be typed with a consistent capitalization of letters.

So identifiers Time, TIme and TIME will have different meanings in JavaScript.

NOTE: Care should be taken while writing your variable and function names in JavaScript.

E.g.
Java Script is basically case-sensitive programming. A function named "Myfunction" is not equal to "MyFunction" &a
variable named "MyVar" is not the same as "Myvar".

Vizu.chowdary@gmail.com JSCRIPT - 26
******************************NOTES: ******************************
SCRIPT:
Generally script or <script > tag contains following 2 essential attributes.
1) Language
2) Type.

1) LANGUAGE: This attribute specifies what scripting language we are using.


2) TYPE: This attribute indicates & recommend to interpreter what value should be set.
E.g: <script language = "javascript" type = "text / javascript">
Javascript code
Javascript code
Javascript code
</script>

JAVA SCRIPT COMMENTS:


Comments are non-executable statements or ignore statements. Using this comment notations we can declare
customized state as for the end user requirement. In JAVASCRIPT, comment notations are divided into following 2 types:
1) Single Line comments.
2) Multi Line comments

1) SINGLE LINE COMMENTS: These comments are restricted to within the line.
The notation is // (Double Forward Slash)

E.G. document.write ("HELLO"); //This will write "HELLO"

2) MULTI LINE COMMENTS: These comments are related to multiple java statements are multiple lines.
The notation is /* */
E.G.
/*
document.write("HELLO");
document.write("<h1> This is a header</h1>")
*/

DEBUGGING JAVASCRIPT ERRORS:


Generally javascript is a disable component in browsers. We should enable JAVASCRIPT option manually.

Vizu.chowdary@gmail.com JSCRIPT - 27
<SCRIPT> TAG DESCRIPTION:
 It is a tag which indicates script interpreter required to escalate lines between
<script>
------------------
------------------
</script> these tags.

 If you did not mention <script> tag, Browser interprets are printing as normal strings. These strings displayed on
the webpage.
<html>
<head>
<script type = "text/javascript">
document.write("it is 'LIVE' script");
document.write("<br/>");
document.write("It is javascript from Netscape");
</script>
</head>
</html>
WORKING WITH SINGLE & DOUBLE QUOTES IN JAVASCRIPT:
Single & double quotes to produce the same results.
Will make you a clear picture on Single & double quotes.

<script type = "text/javascript">


document.write("it is 'LIVE' script");
document.write("<br/>");
document.write('It is "javascript" from Netscape');
document.write('javascript" is "NOT" java');
</script>

EXAMPLE ON DOUBLE QUOTES (“)

No Output for this.

Vizu.chowdary@gmail.com JSCRIPT - 28
There is an escape character \ before. The java script will ignore. With \ I can display the double quotes

OUTPUT:

WORKING WITH JAVASCRIPT SPECIAL CHARACTERS:


In JAVASCRIPT, you can add Special characters to a text screen by using / (back slash) sign.
Insert a special character:
Black slash is used to insert apostrophes, new lines, quotes & other special characters in to a text screen.

E.g. (1)
<script>
var txt = "we are the so-called 'GOOD' from the SOUTH.";
document.write(txt);
</script>

E.g. (2)
<script>
var txt = "we are the so-called "GOOD" from the SOUTH.";
document.write(txt);
</script>

Output: BLANK.

E.g. (3)
<script>
var txt = "we are the so-called \"GOOD\" from the SOUTH.";
document.write(txt);
</script>

Vizu.chowdary@gmail.com JSCRIPT - 29
CODE OUTPUT
\' Single Quote
\" Double Quote
\\ Back Slash
\n New line
\r Carriage Return
\t Tab
\b Backspace
\f Form feed

BREAK UP A CODE LINE:

We can break up a code line with in a text string with a back slash.

<script>
document.write("HELLO \ WORLD!");
</script>

Difference between document.write & window.document.write

There is no difference between the above statements. Here, the window object is highest level object. It contain other
objects & their methods.
Document is object content inside the window objects. WRITE is a method of document object.
In that situation, window object is not necessary.

E.g.
<script>
document.write("HelloWorld!");
document.write("<br>");
window.document.write("BVK");
</script>

E.g.
<script>
document.write("Hello World!");
document.write("BVK");
</script>

Vizu.chowdary@gmail.com JSCRIPT - 30
ENABLING JAVASCRIPT IN BROWSERS

JavaScript in Internet Explorer:


Here are simple steps to turn on or turn off JavaScript in your Internet Explorer:

1) Follow Tools-> Internet Options from the menu


2) Select Security tab from the dialog box
3) Click the Custom Level button
4) Scroll down till you find Scripting option
5) Select Enable radio button under Active scripting
6) Finally click OK and come out
To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under Active scripting.

JavaScript in Firefox:
Here are simple steps to turn on or turn off JavaScript in your Firefox:
1) Follow Tools-> Options
from the menu
2) Select Content option from the dialog box
3) Select Enable JavaScript checkbox
4) Finally click OK and come out
To disable JavaScript support in your Firefox, you should not select Enable JavaScript checkbox.

JavaScript in Opera:
Here are simple steps to turn on or turn off JavaScript in your Opera:
1) Follow Tools-> Preferences
from the menu
2) Select Advanced option from the dialog box
3) Select Content from the listed items
4) Select Enable JavaScript checkbox
5) Finally click OK and come out

To disable JavaScript support in your Opera, you should not select Enable JavaScript checkbox.

Vizu.chowdary@gmail.com JSCRIPT - 31
JAVASCRIPT PLACEMENT IN HTML FILE

There is a flexibility given to include JavaScript code anywhere in an HTML document. But there are following most
preferred ways to include JavaScript in your HTML file.

 Script in <head>...</head> section. (This is preferred)


 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in and external file and then include in <head>...</head> section.

In the following section we will see how we can put JavaScript in different ways:

JavaScript in <head>...</head> section:

If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in
the head as follows:

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 32
JavaScript in <body>...</body> section:

If you need a script to run as the page loads so that the script generates content in the page, the script goes in the
<body> portion of the document. In this case you would not have any function defined using JavaScript:

<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>

JavaScript in <body> and <head> sections:

You can put your JavaScript code in <head> and <body> section altogether as follows:

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 33
JavaScript in External File:

 As you begin to work more extensively with JavaScript, you will likely find that there are cases where you are
reusing identical JavaScript code on multiple pages of a site.
 You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a
mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.
 Here is an example to show how you can include an external JavaScript file in your HTML code using script tag
and its src attribute:

<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>

To use JavaScript from an external file source, you need to write your all JavaScript source code in a simple text file with
extension ".js" and then include that file as shown above.

For example, you can keep following content in filename.js file and then you can use sayHello function in your HTML file
after including filename.js file:

function sayHello() {
alert("Hello World")
}

EXTERNAL JAVA SCRIPT Explanation in detail


Javascript can be placed I External Java Script files. Extension is .JS
Note: External script cannot contain <script> tag.

To use external script, point to .js file, we are using “SRC” attribute.

To use external script file follow the following steps:

STEP 1: Create javascript file & save with .js extension.


Document.write(“<h1> WELCOME to JS EXTERNAL PROGRAMMING!!</h1>”);

STEP 2: Prepare html file & call the JAVA SCRIPT.

<html>
<head>
<script type = “text/javascript” src = “myscript.js”> </script>
</head>
<body>
</body>
</html>
Save file with .html extension or .html extension

Vizu.chowdary@gmail.com JSCRIPT - 34
PREPARE JAVA SCRIPT (SAVE AS .JS FILE)
function show_alert()
{
alert("HI");
}

function show_confirm()
{
confirm("HELLOW");
}

PREPARE HTML SCRIPT (SAVE AS .HTML/.HTM FILE)


<html>
<head>
<script type = "text / javascript" src = "myscript.js"> </script>
</head>
<body>
<button onclick = "SHOW_ALERT()"> SHOW </button>
<button onclick = "SHOW_CONFIRM()"> SHOW_CONFIRM </button>
</body>
</html>

JAVASCRIPT VARIABLES AND DATATYPES

JavaScript DataTypes:
One of the most fundamental characteristics of a programming language is the set of data types it supports.
These are the type of values that can be represented and manipulated in a programming language.

JavaScript allows you to work with three primitive data types:

 Numbers eg. 123, 120.50 etc.

 Strings of text e.g. "This text string" etc.

 Boolean e.g. true or false.

JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value.

In addition to these primitive data types, JavaScript supports a composite data type known as object. We will
see an object detail in a separate chapter.

Note: Java does not make a distinction between integer values and floating-point values. All numbers in
JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-
point format defined by the IEEE 754 standard.

Vizu.chowdary@gmail.com JSCRIPT - 35
Declaring variables:

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 36
I am over writing this program.
What is the data type of this variable?

OUTPUT:

Java Script takes the type of variable dynamically. We need not worry of declaring a data type for a variable.

Type of variable

Vizu.chowdary@gmail.com JSCRIPT - 37
HOW JAVA SCRIPT IS INTERPRETED?
Done at the Browser. Browser has to understand HTML, Jscript.

Vizu.chowdary@gmail.com JSCRIPT - 38
JavaScript Variables:

RULES:
 Every Variable should starts with an Alphabet or Underscore.
 Variable should not contain un-necessary special characters.
 Variable should not contain embedded periods. (dots).
 Variable are case sensitive.
 Count, count and COUNT are 3 different variables.
 Variable should be reasonable length.
 Variables declared with ‘var’ keyword.

VARIANT: collection of data types.

EXAMPLE: Var x;
Var carname;
These are the empty variables. If you want, you can assign values to these variables.
Var x = 5;
Var name = “BVK”.

Write a script, display sum of 2 number.


<html>
<head>
<title> VARIABLES </title>
</head>
<body>
<script type = "text/javascript">
var a = 10;
var b = 20;
var c = a + b;
document.write("the value of a is:" +a);
document.write("<br>");
document.write("the value of b is:" +b);
document.write("<br>");
document.write("the value of c is:" +c);
document.write("<br>");
</script>
</body>
</html>

Note: We are using + operator to concatenate string and number all together. JavaScript does not mind in
adding numbers into strings.

Vizu.chowdary@gmail.com JSCRIPT - 39
Write a script, to read 2 values, to display sum and difference.
<html>
<head>
<title> VARIABLES </title>
</head>
<script type = "text/javascript">
var a = prompt("Enter any value:", "10");
var b = prompt("Enter any value:", "20");
var c = a + b;
var d = a - b;
document.write("the value of a is:" +a);
document.write("<br>");
document.write("the value of b is:" +b);
document.write("<br>");
document.write("the value of c is:" +c);
document.write("<br>");
document.write("the value of d is:" +d);
</script>

<body> </body>
</html>

JavaScript Variable Scope:


The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only
two scopes.
 Global Variables: A global variable has global scope which means it is defined everywhere in your
JavaScript code.
 Local Variables: A local variable will be visible only within a function where it is defined. Function
parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If
you declare a local variable or function parameter with the same name as a global variable, you effectively
hide the global variable. Following example explains it:
<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>

Vizu.chowdary@gmail.com JSCRIPT - 40
JavaScript Variable Names:
While naming your variables in JavaScript keep following rules in mind.
 You should not use any of the JavaScript reserved keyword as variable name. For
example, break or boolean variable names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the
underscore character. For example, 123test is an invalid variable name but_123test is a valid one.
 JavaScript variable names are case sensitive. For example, Name and name are two different variables.
JavaScript Reserved Words:
The following are reserved words in JavaScript. They cannot be used as JavaScript variables, functions,
methods, loop labels, or any object names.
abstract else instanceof switch
boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super

Vizu.chowdary@gmail.com JSCRIPT - 41
PROGRAM:

HTML FILE

CONTENT IN THE BODY

JSCRIPT FILE

It is like inside document -> write -> “HELLO EVERY ONE”

All Jscript statements, mostly ends with semi-colon.

Vizu.chowdary@gmail.com JSCRIPT - 42
In any browser, title bar, tool bar, address bar is called as WINDOW OBJECT.

Tool bar is called as a DOCUMENT.

Vizu.chowdary@gmail.com JSCRIPT - 43
PROGRAM:

Within the document I can use html tag <br> <h1> </h1>

We can place script with in <head> </head> or <body> </body>

EXECUTE in FIREFOX

Vizu.chowdary@gmail.com JSCRIPT - 44
Here we are not getting JSCRIT TEXT.

Let me check with Mozilla by pressing F12

If you don’t want to get this

Use this

Now you don’t get those errors.

Vizu.chowdary@gmail.com JSCRIPT - 45
Wontedly, I made an error

EXECUTE IN CHROME.

Here we are not getting Jscript text.

Press F12

LINE 9

Click on it

Vizu.chowdary@gmail.com JSCRIPT - 46
This is the screen which I get after clicking

CLICK ON THIS

COME TO YELLOW COLOR AND TURNS TO NORMAL

So this is the error.


Number of Errors

Vizu.chowdary@gmail.com JSCRIPT - 47
A CONSOLE FOR DISPLAYING ERRORS/LOGS
A DEBUGGER

BROWSER KEYBOARD
FIREFOX F12
MICROSOFT IE F12
CHROME F12
SAFARI CTRL+ALT+I
OPERA CTRL+ALT+I

WE WILL COME TO KNOW DEBUG AFTER DECLARING VARIABLES.

Vizu.chowdary@gmail.com JSCRIPT - 48
VARIABLE DECLARATIONS
 Variable names must begin with a letter
 Variable names can also begin with $ and _
 Variable names are case sensitive.
 Reserved words (like JavaScript keywords) cannot be used as variable names.

Generally, naming conventions we will start with lower letters

This is wrong. We need to mention it as document.write(myVariable)


The data type that generally declare in Java Script will take dynamically

myVariable = 23 ------------------- this is number

myVariable = ‘23’ ------------------- More like a string


PROGRAM - 3:

Vizu.chowdary@gmail.com JSCRIPT - 49
PROGRAM - 4:

Output is 2.4.

No need to specify the data type. Dynamically it takes. This is one of advantage.

DATA TYPES
 In JavaScript there are 5 different data types that can contain values:
o string
o number
o Boolean
o Object (will discuss later).
o Function (will discuss later).
 JavaScript has Dynamic Types

Boolean: TRUE / FALSE

BOOLEAN TEXT

Vizu.chowdary@gmail.com JSCRIPT - 50
JAVASCRIPT OPERATORS

WHAT IS AN OPERATOR?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is
called operator. JavaScript language supports following type of operators.
 Arithmetic Operators
 Comparison Operators / Assignment Operators
 Logical (or Relational) Operators
 Conditional (or ternary) Operators
Let’s have a look on all operators one by one.

The Arithmetic Operators:


There are following arithmetic operators supported by JavaScript language:
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denumerator B / A will give 2
% Modulus Operator and remainder of after an integer B % A will give 0
division
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9

Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".

Vizu.chowdary@gmail.com JSCRIPT - 51
<html>
<body>

<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);

b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
Vizu.chowdary@gmail.com JSCRIPT - 52
//-->
</script>

<p>Set the variables to different values and then try...</p>


</body>
</html>

Result

a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
a++ = 33
b-- = 10

Set the variables to different values and then try...

The Comparison Operators / Assignment Operators:


There are following comparison operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
== Checks if the value of two operands are equal or not, if yes (A == B) is not true.
then condition becomes true.
!= Checks if the value of two operands are equal or not, if (A != B) is true.
values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value (A > B) is not true.
of right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal (A >= B) is not true.
to the value of right operand, if yes then condition becomes
true.
<= Checks if the value of left operand is less than or equal to (A <= B) is true.
the value of right operand, if yes then condition becomes
true.

Vizu.chowdary@gmail.com JSCRIPT - 53
<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
Result
var b = 20;
var linebreak = "<br />"; (a == b) => false
(a < b) => true
document.write("(a == b) => "); (a > b) => false
result = (a == b);
(a != b) => true
document.write(result);
(a >= b) => false
document.write(linebreak);
(a <= b) => true
document.write("(a < b) => ");
result = (a < b); Set the variables to different values and different
document.write(result); operators and then try...
document.write(linebreak);

document.write("(a > b) => ");


result = (a > b);
document.write(result);
document.write(linebreak);

document.write("(a != b) => ");


result = (a != b);
document.write(result);
document.write(linebreak);

document.write("(a >= b) => ");


result = (a >= b);
document.write(result);
document.write(linebreak);

document.write("(a <= b) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 54
The Logical Operators:
There are following logical operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
&& Called Logical AND operator. If both the operands are non (A && B) is true.
zero then then condition becomes true.
|| Called Logical OR Operator. If any of the two operands are (A || B) is true.
non zero then then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical !(A && B) is false.
state of its operand. If a condition is true then Logical NOT
operator will make false.

<html>
<body>
Result:
<script type="text/javascript">
<!-- (a && b) => false
var a = true; (a || b) => true
var b = false; !(a && b) => true
var linebreak = "<br />";

document.write("(a && b) => "); Set the variables to different values and
result = (a && b); different operators and then try...
document.write(result);
document.write(linebreak);

document.write("(a || b) => ");


result = (a || b);
document.write(result);
document.write(linebreak);

document.write("!(a && b) => ");


result = (!(a && b));
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 55
The Bitwise Operators:
There are following bitwise operators supported by JavaScript language
Assume variable A holds 2 and variable B holds 3 then:
Operator Description Example
& Called Bitwise AND operator. It performs a Boolean AND operation on each (A & B) is 2 .
bit of its integer arguments.
| Called Bitwise OR Operator. It performs a Boolean OR operation on each bit (A | B) is 3.
of its integer arguments.
^ Called Bitwise XOR Operator. It performs a Boolean exclusive OR operation (A ^ B) is 1.
on each bit of its integer arguments. Exclusive OR means that either operand
one is true or operand two is true, but not both.
~ Called Bitwise NOT Operator. It is a is a unary operator and operates by (~B) is -4 .
reversing all bits in the operand.
<< Called Bitwise Shift Left Operator. It moves all bits in its first operand to the (A << 1) is 4.
left by the number of places specified in the second operand. New bits are
filled with zeros. Shifting a value left by one position is equivalent to
multiplying by 2, shifting two positions is equivalent to multiplying by 4, etc.
>> Called Bitwise Shift Right with Sign Operator. It moves all bits in its first (A >> 1) is 1.
operand to the right by the number of places specified in the second
operand. The bits filled in on the left depend on the sign bit of the original
operand, in order to preserve the sign of the result. If the first operand is
positive, the result has zeros placed in the high bits; if the first operand is
negative, the result has ones placed in the high bits. Shifting a value right one
place is equivalent to dividing by 2 (discarding the remainder), shifting right
two places is equivalent to integer division by 4, and so on.
>>> Called Bitwise Shift Right with Zero Operator. This operator is just like the >> (A >>> 1) is 1.
operator, except that the bits shifted in on the left are always zero,

Vizu.chowdary@gmail.com JSCRIPT - 56
<html>
<body>

<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";

document.write("(a & b) => ");


result = (a & b);
document.write(result);
document.write(linebreak);

document.write("(a | b) => ");


result = (a | b); Result
document.write(result);
document.write(linebreak); (a & b) => 2
(a | b) => 3
document.write("(a ^ b) => "); (a ^ b) => 1
result = (a ^ b); (~b) => -4
document.write(result); (a << b) => 16
document.write(linebreak);
(a >> b) => 0
document.write("(~b) => ");
Set the variables to different values and different
result = (~b);
operators and then try...
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);

document.write("(a >> b) => ");


result = (a >> b);
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 57
The Assignment Operators:
There are following assignment operators supported by JavaScript language:
Operator Description Example
= Simple assignment operator, Assigns values from right side C = A + B will assigne value of A + B
operands to left side operand into C
+= Add AND assignment operator, It adds right operand to the C += A is equivalent to C = C + A
left operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C = C - A
operand from the left operand and assign the result to left
operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C = C * A
operand with the left operand and assign the result to left
operand
/= Divide AND assignment operator, It divides left operand C /= A is equivalent to C = C / A
with the right operand and assign the result to left operand
%= Modulus AND assignment operator, It takes modulus using C %= A is equivalent to C = C % A
two operands and assign the result to left operand
Note: Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.

Vizu.chowdary@gmail.com JSCRIPT - 58
<html>
<body>

<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";

document.write("Value of a => (a = b) => ");


result = (a = b);
document.write(result); RESULT
document.write(linebreak); Value of a => (a = b) => 10
Value of a => (a += b) => 20
document.write("Value of a => (a += b) => "); Value of a => (a -= b) => 10
result = (a += b); Value of a => (a *= b) => 100
document.write(result); Value of a => (a /= b) => 10
document.write(linebreak); Value of a => (a %= b) => 0

document.write("Value of a => (a -= b) => "); Set the variables to different values


result = (a -= b); and different operators and then try...
document.write(result);
document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a /= b) => ");


result = (a /= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a %= b) => ");


result = (a %= b);
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 59
Miscellaneous Operator
The Conditional Operator (? :)
There is an operator called conditional operator. This first evaluates an expression for a true or false value and
then execute one of the two given statements depending upon the result of the evaluation. The conditioanl
operator has this syntax:

Operator Description Example


?: Conditional Expression If Condition is true ? Then value X : Otherwise value Y

<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Result

((a > b) ? 100 : 200) => 200


((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...

Vizu.chowdary@gmail.com JSCRIPT - 60
The typeof Operator

 The typeof is a unary operator that is placed before its single operand, which can be of any type. Its
value is a string indicating the data type of the operand.
 The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or
boolean value and returns true or false based on the evaluation.
 Here is the list of return values for the typeof Operator :
Type String Returned by typeof
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"

<html> RESULT
<body>
Result => B is String
<script type="text/javascript"> Result => A is Numeric
<!--
var a = 10; Set the variables to different values and
var b = "String"; different operators and then try...
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 61
STRING CONCATENATION (+)
There + operator used on strings. To add 2 strings variables this operator is required.

Eg.
Str1 = “NIL”;
Str2 = “PIN2”;
Str3 = Str1 + str2;

Program

<html>
<body>
<script type = "text/javascript">
var x;

x = 1 + 5;
document.write(x);
document.write("<br>");

x = 1 + "5";
document.write(x);
document.write("<br>");

x = "1" + "5";
document.write(x);
document.write("<br>");

</script>
</body>
</html>

Result

6
15
15

Vizu.chowdary@gmail.com JSCRIPT - 62
• IF

• SWITCH

• WHILE

• DO..WHILE

• FOR

Vizu.chowdary@gmail.com JSCRIPT - 63
JAVASCRIPT IF………..ELSE

While writing a program, there may be a situation when you need to adopt one path out of the given two
paths. So you need to make use of conditional statements that allow your program to make correct decisions
and perform right actions.
JavaScript supports conditional statements which are used to perform different actions based on different
conditions. Here we will explain if..else statement.
JavaScript supports following forms of if..else statement:
 if statement
 if...else statement
 if...else if... statement.

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
}

Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) are executed.
If expression is false then no statement would be not executed. Most of the times you will use comparison
operators while making decisions.

<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>

Vizu.chowdary@gmail.com JSCRIPT - 64
<html>
<body>

<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

Result

Qualifies for driving

Set the variable to different value and then try...

if...else statement:

The if...else statement is the next form of control statement that allows JavaScript to execute statements in
more controlled way.

if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}

Vizu.chowdary@gmail.com JSCRIPT - 65
<html>
<body>

<script type="text/javascript">
<!--
var age = 15;

if( age > 18 ){


document.write("<b>Qualifies for driving</b>");
}else{
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

Result

Does not qualify for driving

Set the variable to different value and then try...

if...else if... statement:


The if...else if... statement is the one level advance form of control statement that allows JavaScript to make
correct decision out of several conditions.

if (expression 1){
Statement(s) to be executed if expression 1 is true
}else if (expression 2){
Statement(s) to be executed if expression 2 is true
}else if (expression 3){
Statement(s) to be executed if expression 3 is true
}else{
Statement(s) to be executed if no expression is true
}

Vizu.chowdary@gmail.com JSCRIPT - 66
<html>
<body>

<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
document.write("<b>Economics Book</b>");
}else{
document.write("<b>Unknown Book</b>");
}
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

Result

Maths Book

Set the variable to different value and then try...

Vizu.chowdary@gmail.com JSCRIPT - 67
JAVASCRIPT SWITCH CASE

You can use multiple if...else if statements, to perform a multiway branch. However, this is not always the
best solution, especially when all of the branches depend on the value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does
so more efficiently than repeated if...else if statements.
Syntax:
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. The interpreter checks eachcase against the value of the
expression until a match is found. If nothing matches, a default condition will be used.

switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}

The break statements indicate to the interpreter the end of that particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.
We will explain break statement in Loop Control chapter.

Vizu.chowdary@gmail.com JSCRIPT - 68
<html>
<body>

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

RESULT

Entering switch block


Good job
Exiting switch block

Set the variable to different value and then try...

Vizu.chowdary@gmail.com JSCRIPT - 69
Consider a case if you do not use break statement:

<html>
<body>

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

Result

Entering switch block


Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block

Set the variable to different value and then try...

Vizu.chowdary@gmail.com JSCRIPT - 70
JAVASCRIPT WHILE LOOP

While writing a program, there may be a situation when you need to perform some action over and over
again. In such situation you would need to write loop statements to reduce the number of lines.
JavaScript supports all the necessary loops to help you on all steps of programming.
The while Loop
The most basic loop in JavaScript is the while loop which would be discussed in this tutorial.
Syntax:
WHILE (EXPRESSION){
STATEMENT(S) TO BE EXECUTED IF EXPRESSION IS TRUE
}
The purpose of a while loop is to execute a statement or code block repeatedly as long asexpression is true.
Once expression becomes false, the loop will be exited.

<html>
<body> Starting LoopCurrent Count : 0
Current Count : 1
<script type="text/javascript"> Current Count : 2
<!--
Current Count : 3
var count = 0;
Current Count : 4
document.write("Starting Loop");
Current Count : 5
while (count < 10){
Current Count : 6
document.write("Current Count : " + count + "<br />");
count++; Current Count : 7
} Current Count : 8
document.write("Loop stopped!"); Current Count : 9
//--> Loop stopped!
</script>
Set the variable to different value and then try...
<p>Set the variable to different value and then try...</p>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 71
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);

Note the semicolon used at the end of the do...while loop.

Let us write above example in terms of do...while loop.

<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
document.write("Current Count : " + count + "<br />");
count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>

Result

Starting Loop
Current Count : 0
Loop stopped!

Vizu.chowdary@gmail.com JSCRIPT - 72
JAVASCRIPT FOR LOOP

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.
You can put all the three parts in a single line separated by a semicolon.

for (initialization; test condition; iteration statement){


Statement(s) to be executed if test condition is true
}
Starting Loop
Current Count : 0
<html> Current Count : 1
<body> Current Count : 2
Current Count : 3
<script type="text/javascript"> Current Count : 4
<!-- Current Count : 5
var count; Current Count : 6
document.write("Starting Loop" + "<br />"); Current Count : 7
for(count = 0; count < 10; count++){ Current Count : 8
document.write("Current Count : " + count ); Current Count : 9
document.write("<br />"); Loop stopped!
}
document.write("Loop stopped!"); Set the variable to different value and then try...
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 73
JAVASCRIPT FOR……IN LOOP

There is one more loop supported by JavaScript. It is called for...in loop. This loop is used to loop through an
object's properties.
Because we have not discussed Objects yet, so you may not feel comfortable with this loop. But once you will
have understanding on JavaScript objects then you will find this loop very useful.

for (variablename in object){


statement or block to execute
}

In each iteration one property from object is assigned to variablename and this loop continues till all the
properties of the object are exhausted.
Navigator Object Properties
webkitPersistentStorage
<html> webkitTemporaryStorage
<body> geolocation
doNotTrack
OUTPUT onLine
<script type="text/javascript">
languages
<!-- language
var aProperty; userAgent
document.write("Navigator Object Properties<br /> "); product
for (aProperty in navigator) platform
{ appVersion
appName
document.write(aProperty);
appCodeName
document.write("<br />"); hardwareConcurrency
} maxTouchPoints
document.write("Exiting from the loop!"); vendorSub
//--> vendor
</script> productSub
cookieEnabled
mimeTypes
<p>Set the variable to different object and then try...</p> plugins
</body> javaEnabled
</html> getStorageUpdates
vibrate
getBattery
webkitGetGamepads
getGamepads
webkitGetUserMedia
registerProtocolHandler
unregisterProtocolHandler
Exiting from the loop!

Set the variable to different object and then


try...

Vizu.chowdary@gmail.com JSCRIPT - 74
JAVASCRIPT LOOP CONTROL
JavaScript provides you full control to handle your loops and switch statement. There may be a situation when
you need to come out of a loop without reaching at its bottom. There may also be a situation when you want
to skip a part of your code block and want to start next iteration of the look.
To handle all such situations, JavaScript provides break and continue statements. These statements are used
to immediately come out of any loop or to start the next iteration of any loop respectively.
The break Statement:
The break statement, which was briefly introduced with the switch statement, is used to exit a loop early,
breaking out of the enclosing curly braces.
Example:
This example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early
once x reaches 5 and reaches to document.write(..) statement just below to closing curly brace:
We already have seen the usage of break statement inside a switch statement.
<html>
<body>
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

RESULT
Entering the loop
2
3
4
5
Exiting the loop!

Set the variable to different value and then try...

Vizu.chowdary@gmail.com JSCRIPT - 75
The continue Statement:
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip
remaining code block.
When a continue statement is encountered, program flow will move to the loop check expression
immediately and if condition remain true then it start next iteration otherwise control comes out of the loop.
Example:
This example illustrates the use of a continue statement with a while loop. Notice how thecontinue statement
is used to skip printing when the index held in variable x reaches 5:

<html>
<body>

<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skill rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
RESULT
Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!

Vizu.chowdary@gmail.com JSCRIPT - 76
Set the variable to different value and then try...

Using Labels to Control the Flow:


Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely.
A label is simply an identifier followed by a colon that is applied to a statement or block of code. We will see
two different examples to understand label with break and continue.
Note: Line breaks are not allowed between the continue or break statement and its label name. Also, there
should not be any other statement in between a label name and associated loop.

<html>
<body>
Entering the loop!
<script type="text/javascript"> Outerloop: 0
<!-- Innerloop: 0
document.write("Entering the loop!<br /> "); Innerloop: 1
outerloop: // This is the label name Innerloop: 2
for (var i = 0; i < 5; i++)
Innerloop: 3
{
Outerloop: 1
document.write("Outerloop: " + i + "<br />");
Innerloop: 0
innerloop:
Innerloop: 1
for (var j = 0; j < 5; j++)
{ Innerloop: 2
if (j > 3 ) break ; // Quit the innermost loop Innerloop: 3
if (i == 2) break innerloop; // Do the same thing Outerloop: 2
if (i == 4) break outerloop; // Quit the outer loop Outerloop: 3
document.write("Innerloop: " + j + " <br />"); Innerloop: 0
} Innerloop: 1
} Innerloop: 2
document.write("Exiting the loop!<br /> "); Innerloop: 3
//--> Outerloop: 4
</script> Exiting the loop!

</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 77
<html>
<body>

<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: // This is the label name
for (var i = 0; i < 3; i++)
{
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++)
{
if (j == 3){
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

</body>
</html>

RESULT
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!

Vizu.chowdary@gmail.com JSCRIPT - 78
Vizu.chowdary@gmail.com JSCRIPT - 79
EVENTS
WHAT IS AN EVENT?
Whatever the action that perform by the user.
Event can be, when you are specifying something on the input field user name, that can be a event.
Whatever task done by end user can be called as EVENT.
E.g.
Click on button is an event.

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


• When JavaScript is used in HTML pages, JavaScript can "react" on these events.
• An HTML event can be something the browser does, or something a user does.

EVENTS: On mouse over, Onclick

There are in-built events. (Onmouseover, Onclick)

(OR)

What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user or browser
manipulates a page.
When the page loads, that is an event. When the user clicks a button, that click, too, is an event. Another
example of events are like pressing any key, closing window, resizing window etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows, messages to be displayed to users, data to be validated, and virtually any other type of response
imaginable to occur.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element have a certain set of
events which can trigger JavaScript Code.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see few
examples to understand a relation between Event and JavaScript:
onclick Event Type:
This is the most frequently used event type which occurs when a user clicks mouse left button. You can put
your validation, warning etc against this event type.

Vizu.chowdary@gmail.com JSCRIPT - 80
PROGRAM:
EVENT: onclick

Onclick is an event (inline javascript code). ONCLICK is in built event. Specified by html & JSCRIPT.
------------------------------------------:OUTPUT: ------------------------------------------

Click on these button and find the output.

Vizu.chowdary@gmail.com JSCRIPT - 81
PROGRAM :
EVENT: onmouseover

OUTPUT:

You don’t need to click on this. Just take mouse on it. Alert message will be displayed.

PROGRAM:

Assignment: when I take mouse on this, input field has to show me yellow color. Can be done by combination of CSS and
JAVA.

Vizu.chowdary@gmail.com JSCRIPT - 82
PROGRAM: (this program is included with FUNCTIONS)

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 83
onsubmit event type:

 Another most important event type is onsubmit. This event occurs when you try to submit a form. So
you can put your form validation against this event type.
 Here is simple example showing its usage. Here we are calling a validate() function before submitting a
form data to the webserver. If validate() function returns true the form will be submitted otherwise it
will not submit the data.
onmouseover and onmouseout:

These two event types will help you to create nice effects with images or even with text as well.
The onmouseover event occurs when you bring your mouse over any element and the onmouseoutoccurs
when you take your mouse out from that element.

Vizu.chowdary@gmail.com JSCRIPT - 84
HTML 4 Standard Events
The standard HTML 4 events are listed here for your reference. Here script indicates a Javascript function to be
executed against that event.

Event Value Description


onchange script Script runs when the element changes
onsubmit script Script runs when the form is submitted
onreset script Script runs when the form is reset
onselect script Script runs when the element is selected
onblur script Script runs when the element loses focus
onfocus script Script runs when the element gets focus
onkeydown script Script runs when key is pressed
onkeypress script Script runs when key is pressed and released
onkeyup script Script runs when key is released
onclick script Script runs when a mouse click
ondblclick script Script runs when a mouse double-click
onmousedown script Script runs when mouse button is pressed
onmousemove script Script runs when mouse pointer moves
onmouseout script Script runs when mouse pointer moves out of an element
onmouseover script Script runs when mouse pointer moves over an element
onmouseup script Script runs when mouse button is released

Vizu.chowdary@gmail.com JSCRIPT - 85
Vizu.chowdary@gmail.com JSCRIPT - 86
FUNCTIONS
 A function is a group of reusable code which can be called anywhere in your program. This eliminates
the need of writing same code again and again. This will help programmers to write modular code. You
can divide your big program in a number of small and manageable functions.
 Like any other advance programming language, JavaScript also supports all the features necessary to
write modular code using functions.
 You must have seen functions like alert() and write() in previous source. We are using these function
again and again but they have been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section will explain you how to write your own
functions in JavaScript.

Function Definition:

Before we use a function we need to define that function. 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. The basic syntax is shown here:

Syntax: Function function_name (parameter_list)


{

• A JavaScript function is a block of code designed to perform a particular task.


• It can acts as event handler. (when click on a button what should happen, that is called as event handler)

Vizu.chowdary@gmail.com JSCRIPT - 87
CALLING THE FUNCTION
To invoke a function somewhere later in the script, you would simple need to write the name of that function
as follows:

Vizu.chowdary@gmail.com JSCRIPT - 88
OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 89
ADVANTAGES:
Function like function modules.
Functions are re-usable.

PROGRAM – 8.1: RE-USE OF FUNCTIONS

Vizu.chowdary@gmail.com JSCRIPT - 90
Function Parameters:

Till now we have seen function without a parameters. But there is a facility to 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.

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 from the function to return
their multiplication in your calling program.
E.G.
This function takes two parameters and concatenates them and return resultant in the calling program:

<script type="text/javascript">
<!--
function concatenate(first, last)
{
var full;

full = first + last;


return full;
}
//-->
</script>

Now we can call this function as follows:

<script type="text/javascript">
<!--
var result;
result = concatenate('Zara', 'Ali');
alert(result );
//-->
</script>

Vizu.chowdary@gmail.com JSCRIPT - 91
FUNCTION PARAMETERS (SINGLE PARAMETER)
WE CAN USE FUNCTIONS EXTENSIVELY JUST LIKE IMPORT / EXPORT PARAMETERS

EQUIVALENT TO IMPORT PARAMETER

RETURN PARAMETER (NO EXPORT HERE)

QUESTION: WHAT IS DIFFERENCE BETWEEN EXPORT PARAMETERS AND RETURN PARAMETERS FOR AN ABAP
FUNCTION MODULE?

In EXPORT, we can send multiple values – return a complete table.


In RETURN, will only returns a structure – return almost single value.
We cannot use the combo of these two inside a function module. This is not relevant to us now.

Vizu.chowdary@gmail.com JSCRIPT - 92
FUNCTION PARAMETERS (MULTIPLE PARAMETER)

Using HTML and CSS we can design the calculator.


On click on the number button there one more thing, how to capture the values using java script.

Vizu.chowdary@gmail.com JSCRIPT - 93
USING ABOVE PROGRAM FOR RE-USE, WITH SINGLE DOCUMENT.WRITE

Vizu.chowdary@gmail.com JSCRIPT - 94
DEBUGGING

Run in GOOGLE CHROME.

Press F12.

With DEBUGGER, let’s put a break-point. Make changes to it.

Vizu.chowdary@gmail.com JSCRIPT - 95
Close this

This is default page.

This is file name. if you click on this. Code will be opened.

Vizu.chowdary@gmail.com JSCRIPT - 96
Right click on 7th line and select Add breakpoint. (or) click on 7th line

Break Point

Refresh the chrome

Vizu.chowdary@gmail.com JSCRIPT - 97
We can see Paused in debugger. Step-over

F8
Step out of Current Function (Shift + F11)

Step into next function call (F11)

De-activate Break Points

When there is an exception, Pause on EXCEPTION

Vizu.chowdary@gmail.com JSCRIPT - 98
First, we will see how we can go for next step.

Click on step into next function call (F11)

You will get this message. Click on OK.

This is how we debug.


XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Vizu.chowdary@gmail.com JSCRIPT - 99
Now let’s change the value.
Go to the CONSOLE
The is the value that we can see

Press ENTER.

Now Click on STEP OVER (F10)

Vizu.chowdary@gmail.com JSCRIPT - 100


Click on OK

Now De-activate the debugging.

Vizu.chowdary@gmail.com JSCRIPT - 101


OUTPUT

Vizu.chowdary@gmail.com JSCRIPT - 102


EXAMPLE: INTERPRET MORE ON BUTTONS

ONCLICK is the in-built event provided by HTML guys, that if you want to interact with java script

OUTPUT:

When we have a huge program we cannot write here.

When we want to re-use same alert or multiple times. This is not best way. So we do is create something called as
function (like F.M for us). See in next program

Vizu.chowdary@gmail.com JSCRIPT - 103


Syntax of function:

function clickMe(){

Modify above program

Vizu.chowdary@gmail.com JSCRIPT - 104


This program, written with 2 alerts. Executes sequence.

Vizu.chowdary@gmail.com JSCRIPT - 105


EXAMPLE:

There are so many events are there in-built starting with on


Google for more events.
E.g. onmouseover

When I but mouse on the button, it executes the particular function.

OutPut:

Vizu.chowdary@gmail.com JSCRIPT - 106


EXAMPLES: some more functions
Here I am defining inside the function

Let’s change the value of a variable.


Over riding

OUTPUT:
Here I am defining inside the function
Next example I am calling outside the function.
At alert level it is SAP UI5

Vizu.chowdary@gmail.com JSCRIPT - 107


EXAMPLE:
I am calling outside the function.

Output:
When I run it. It is netweaver Gateway training

Vizu.chowdary@gmail.com JSCRIPT - 108


EXAMPLE:

It is GLOBAL VARIABLE (myVariable). Which can be changed by functions.


LOCAL VARIABLE: declare with var. (Var myVariable)

OUTPUT:
It is SAP UI5

Vizu.chowdary@gmail.com JSCRIPT - 109


EXAMPLE:

Vizu.chowdary@gmail.com JSCRIPT - 110


EXAMPLE:

Output:
Here we have an error.
Execute.
Press F12 on browser.

Vizu.chowdary@gmail.com JSCRIPT - 111


localvar is not defined

Unless and until we execute the function, localvar is not known to the system

Vizu.chowdary@gmail.com JSCRIPT - 112


EXAMPLE:
This is global variable

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 113


EXAMPLE: string operation

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 114


WHAT IS THE ROLE OF FUNCTION IN REAL TIME? GENERALLY WHY WE USE FUNCTIONS?
Re-usability.
In SAP, Function module holds parameters (import, exports, tables got deprecated, return, changing)
In JSCRIPT Function HAS IMPORT PARAMETER, FOR EXPORT WE USE GLOBAL VARIABLES, RETURN

Example

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 115


EXAMPLE: PASS MULTIPLE MESSAGES
2 messages and concatenate them

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 116


EXAMPLE: PASS MULTIPLE PARAMETERS AND RETURN

WHAT IS DIFFERENCE BETWEEN RETURN AND EXPORT IN FUNCTION MODULE?


EXPORT: returns multiple
RETURN: returns single

Vizu.chowdary@gmail.com JSCRIPT - 117


EXAMPLE:

Alert is JAVASCRIPT standard keyword. ALERT is inbuilt event.


Return is used to return something from function.

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 118


EXAMPLE:

DOM GETS LOADED INITIALLY (first interpreted).


Javascript works on next and executed later.

Output: no value available for this.

Vizu.chowdary@gmail.com JSCRIPT - 119


EXAMPLE:

The above program I am writing it in a function.

OUTPUT:

Click on This is Para1

You are referring to HTMLParagraphElement which is an object.


What we can determine by above program is; it runs from top to bottom. Executes the script. But it is not aware
because line no. 9 get executed initially. But at that point of time, there is no value.
Para is an object. localVar is an object which is pointing to the para.

Vizu.chowdary@gmail.com JSCRIPT - 120


EXAMPLE: changes to above example

OUTPUT:
Initially null
Press on OK

Click on This is Para1

Loads line by line even though that is script

Vizu.chowdary@gmail.com JSCRIPT - 121


EXAMPLE:
How to get the inner value?
We can get inner value by using the object property / variable called .innerHTML

In JAVA SCRIPT we call variable as property

OUTPUT:
Press on This is Para1

This is the way, how i can get into the DOM and display (getElementByid)

getElementByid() is extensively used in java script.

Vizu.chowdary@gmail.com JSCRIPT - 122


EXAMPLE:
I am commenting alert.

This line is optional, we not using

Click

This is one of the way how JAVASCRIPT works on the DOM by using getElementById().

Let’s see how code gets executed.


Press F12.

Vizu.chowdary@gmail.com JSCRIPT - 123


Put Break-point.
Click on this.

Right click on this, for removing break-point.


Press this for execution

We will get descript over here, for each single step execution. We can also edit here as we do in ABAP debugging.

Vizu.chowdary@gmail.com JSCRIPT - 124


JAVASCRIPT DIALOG BOXES
JAVA SCRIPT HAS 3 KINDS OF POP UP BOXES 1) ALERT BOX 2) CONFIRM BOX 3) PROMPT BOX

JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get
confirmation on any input or to have a kind of input from the users.
Here we will see each dialog box one by one:
Alert Dialog Box:
(USED TO DISPLAY ALERT POP UP, WHEN USER CLICK ON “OK” TO PROCEED TO NEXT STEP.)
SYNTAX: ALERT (“MESSAGE”);
An alert dialog box is mostly used to give a warning message to the users. Like if one input field requires to enter some
text but user does not enter that field then as a part of validation you can use alert box to give warning message as
follows:

<head>
<script type="text/javascript">
<!--
alert("Warning Message");
//-->
</script>
</head>

Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and
proceed.

<html>
<head>
<script type="text/javascript">
<!--
function Warn() {
alert("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 125


Example

<html>

<head>
<title> pop up boxes </title>
<script>
alert("welcome to My Web page");
alert("Bye....");
</script>
</head>

<body>
<script>
alert("welcome to body of the page");
alert("BYE......");
</body>
</html>

Click on ok

Vizu.chowdary@gmail.com JSCRIPT - 126


How to write text on Multiple Lines in an Alert BOX?

 We Should not use <br> tag here, ALERT() is a method of window object that can’t interpret HTML tags.
 If you break text into multiple lines we should use new line escape character. It consist of (\) Back slash symbol
& an alphabet.

The following are commonly used escape characters.

\n Inserts a new line


\t Inserts a tab
\r Carriage return
\b Backspace
\f Form feed
\’ Single quote
\” Double quote
\\ Back slash
EXAMPLE
<script>
alert("javascript\n a \n client_side \n programming \n language");
</script>

EXAMPLE

<script>
alert("1 \n \t 2 \n\t\t 3");
</script>

Vizu.chowdary@gmail.com JSCRIPT - 127


ALERT WITH FUNCTIONS:

<head>
<script>
function show_message()
{
alert("it is alert popup");
alert("bye....");
}
</script>
</head>
<body>
<input type = "SUBMIT" onclick = "show-message()" value = "showMe">
</body>

Vizu.chowdary@gmail.com JSCRIPT - 128


Confirmation Dialog Box:
 It is often used, If you want to verify or accept something when a confirm box pop-up, user should get OK or
CANCEL to proceed.
 If user clicks OK, it returns TRUE, if user click CANCEL, it returns FALSE.
Syntax: CONFIRM (“MESSGE”);
<head>
<script>
xyz = confirm("CLICK OK or CANCEL");
if (xyz ==TRUE)
{
alert("user selected OK button");
}

else
{
alert("USER SELECTED CANCEL BUTTON");
}
</script>
</head>

A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two
buttons: OK and Cancel.
If the user clicks on OK button the window method confirm() will return true. If the user clicks on the Cancel
button confirm() returns false. You can use confirmation dialog box as follows:

<html>
<head>
<script type="text/javascript">
<!--
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
alert("User wants to continue!");
return true;
}else{
alert("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 129


<head>
<script>
function show_confirm()
{
xyz = confirm("click OK or CANCEL");
if (xyz == TRUE)
{
alert("user selected OK button");
}
else
{
alert("user selected CANCEL button");
}
}
</script>
</head>
<body>
<button onclick = "SHOW_CONFIRM()">
show_message
</button>

Vizu.chowdary@gmail.com JSCRIPT - 130


Prompt Dialog Box:
 The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus it enable you to
interact with the user. The user needs to fill in the field and then click OK.
 This dialog box is displayed using a method called prompt() which takes two parameters (i) A label which you
want to display in the text box (ii) A default string to display in the text box.
 This dialog box with two buttons: OK and Cancel. If the user clicks on OK button the window
method prompt() will return entered value from the text box. If the user clicks on the Cancel button the window
method prompt() returns null.
 You can use prompt dialog box as follows:

Syntax:
PROMPT (“SOMETEXT”, “DEFAULT VALUE”);

 A prompt box is used to input a value before entering a page. When a prompt box pops up, a user should click
either OK or CANCEL.
 If user select OK, it returns the INPUT value.
 If user select CANCEL, it returns NULL

<head>
<script>
xyz = prompt("enter any number", "9");
alert("entered Number is: " +xyz);
</script>
</head>

Vizu.chowdary@gmail.com JSCRIPT - 131


<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
alert("You have entered : " + retVal );
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 132


ALERT
Alert();
Alerting the end user.

Conveying the message to end-user is alert.

PROGRAM - 5:

I want the output to be “SAPUI5” with Netweaver Gateway.

But this is throwing error.


We need to re-write the code like this.

\ - escape character (next character will be escaped)

Vizu.chowdary@gmail.com JSCRIPT - 133


Vizu.chowdary@gmail.com JSCRIPT - 134
JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if
it provides four basic capabilities to developers:
 Encapsulation: the capability to store related information, whether data or methods, together in an object
 Aggregation: the capability to store one object inside of another object
 Inheritance: the capability of a class to rely upon another class (or number of classes) for some of its properties
and methods
 Polymorphism: the capability to write one function or method that works in a variety of different ways
Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of the object
otherwise, the attribute is considered a property.

Object Properties:
Object properties can be any of the three primitive data types, or any of the abstract data types, such as another object.
Object properties are usually variables that are used internally in the object's methods, but can also be globally visible
variables that are used throughout the page.
The syntax for adding a property to an object is:
objectName.objectProperty = propertyValue;
Example:
Following is a simple example to show how to get a document title using "title" property of document object:
var str = document.title;

Object Methods:
The methods are functions that let the object do something or let something be done to it. There is little difference
between a function and a method, except that a function is a standalone unit of statements and a method is attached to
an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to performing complex
mathematical operations on a group of local properties and parameters.
Example:
Following is a simple example to show how to use write() method of document object to write any content on the
document:
document.write("This is test");

Vizu.chowdary@gmail.com JSCRIPT - 135


User-Defined Objects:
All user-defined objects and built-in objects are descendants of an object called Object.
The new Operator:
The new operator is used to create an instance of an object. To create an object, the new operator is followed by the
constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in
JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("FEB, 1980");

The Object() Constructor:


A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function
called Object() to build the object. The return value of the Object() constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the object are not variables and are not
defined with the var keyword.

This example demonstrates how to create an object: This example demonstrates how to create an object with a
User-Defined Function. Here thiskeyword is used to refer to
the object that has been passed to a function:
<html>
<head>
<html>
<title>User-defined objects</title>
<head>
<script type="text/javascript">
<title>User-defined objects</title>
var book = new Object(); // Create the object
<script type="text/javascript">
book.subject = "Perl"; // Assign properties to the object
function book(title, author){
book.author = "Mohtashim";
this.title = title;
</script>
this.author = author;
</head>
}
<body>
</script>
<script type="text/javascript">
</head>
document.write("Book name is : " + book.subject +
<body>
"<br>");
<script type="text/javascript">
document.write("Book author is : " + book.author +
var myBook = new book("Perl", "Mohtashim");
"<br>");
document.write("Book title is : " + myBook.title +
</script>
"<br>");
</body>
document.write("Book author is : " + myBook.author +
</html>
"<br>");
</script>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 136


Defining Methods for an Object:
The previous examples demonstrate how the constructor creates the object and assigns properties. But we need to
complete the definition of an object by assigning methods to it.
Example:
Here is a simple example to show how to add a function along with an object:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method


function addPrice(amount){
this.price = amount;
}

function book(title, author){


this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}

</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 137


The with Keyword:
The with keyword is used as a kind of shorthand for referencing an object's properties or methods.
The object specified as an argument to with becomes the default object for the duration of the block that follows. The
properties and methods for the object can be used without naming the object.

Syntax:
with (object){
properties used without the object name and dot
}

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method


function addPrice(amount){
with(this){
price = amount;
}
}
function book(title, author){
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 138


JavaScript Native Objects:
JavaScript has several built-in or native objects. These objects are accessible anywhere in your program and will work
the same way in any browser running in any operating system.
Here is the list of all important JavaScript Native Objects:
 JavaScript Number Object
 JavaScript Boolean Object
 JavaScript String Object
 JavaScript Array Object
 JavaScript Date Object
 JavaScript Math Object
 JavaScript RegExp Object

Vizu.chowdary@gmail.com JSCRIPT - 139


JAVASCRIPT ARRAY OBJECT

HTML
Java Script works on the DOM. Whenever Browser Executes the HTML. It creates a DOM.

ARRAYS
WHAT IS THE SIGNIFICANCE OF ARRAY?
Stack of values where we can manipulate.
We can add-up multiple values, instead of holding a single value in form of variable.
Collection of elements.

Arrays are not used extensively. Before OOP’s they used this. Let me add up some java script over here also.

• It’s like internal table concept

I am creating an object of type Array and I am naming it as cars.


This is how an object in java script can be declared.

I am creating an in built class Array (class definition is available)

Vizu.chowdary@gmail.com JSCRIPT - 140


Whenever we specify new -> it refers to an object, an in-built array object of java script gets created and within that we
passing the value (“ferari”, “hundai”, “maruthi”, “swift”);

WHAT IS THE SIGNIFICANCE OF NEW? WHAT IS THE NEED?


NEW is a keyword to create memory for that object (creation means allocation of the memory to store the values)
(Creating an instance.)

OUTPUT:
There will be no output for above example. We need to call the function.

Function is not called.

Vizu.chowdary@gmail.com JSCRIPT - 141


Modify above program, call the function explicitly.

OUTPUT:

Whenever we are calling, the window gets called.


Another way around is window.onload = myArray; (instead of myArray(); )
Window gets loaded, call function.

Vizu.chowdary@gmail.com JSCRIPT - 142


EXAMPLE ON ARRAY:

Vizu.chowdary@gmail.com JSCRIPT - 143


EXAMPLE: add content to arrays dynamically (another way)

EXAMPLE: I have added only 2 arrays. The length of arrays will be

OUTPUT:I have added only 2 arrays. The length of arrays will be

EXAMPLE: now I am removing number inside Array(), what would be length

OUTPUT: 2 (dynamically it takes)

Vizu.chowdary@gmail.com JSCRIPT - 144


EXAMPLE:

Here Memory allocation we had given 3 {new Array(3)}.

It takes all dynamically, that is the behavior.

Vizu.chowdary@gmail.com JSCRIPT - 145


Vizu.chowdary@gmail.com JSCRIPT - 146
EXAMPLE: read the elements from FORM
Whatever the input I had provided, it should show on top. How to achieve this

(1) We need to get the reference of the para.


(2) Concatenate the value with input value. How to retrieve is;
Case sensitive

We can also put single quotes ‘ ‘

Form we can use, when we want send the data from this page to another page (or 3rd party).
Here we are working on single document. So the code above.

Note: DOM not only holds element (model) and also holds value that we had provided.
With help of DOM we can retrieve value with in the input.

Output:

Vizu.chowdary@gmail.com JSCRIPT - 147


EXAMPLE: same above program with some easy modification

We can omit var and directly write

Vizu.chowdary@gmail.com JSCRIPT - 148


EXAMPLE:

Output:

Explanation…………………..

Vizu.chowdary@gmail.com JSCRIPT - 149


EXPLANATION FOR ABOVE PROGRAM:
Algorithm: requirement is to write “welcome” + name in the para

1) Get the reference of para.

2) Retrieve value of name

3) Concatenation
4) Assigned valued to the inner part of para

Vizu.chowdary@gmail.com JSCRIPT - 150


EXAMPLE:
First page: I have user id and password with login
User if user has not entered one of them, should remain on the same page. Otherwise it can move to second page.

Initially (not complete)


1st file

2nd file

Vizu.chowdary@gmail.com JSCRIPT - 151


1st page in the place of form I added second page file. (not complete)

Click on login without giving values. Navigates to second page.

Now requirement is, if user doesn’t enter any values, it should not navigate to second page. Should remain on same
page.

Continues………………..

Vizu.chowdary@gmail.com JSCRIPT - 152


Click on login

When you click on OK, its navigation to second page

Vizu.chowdary@gmail.com JSCRIPT - 153


Bug in program, correct it.
I am calling function on the button, that button doesn’t validate.

For returning on the same page, we need to validate at form level.


So corrections

Validation should be done on FORM level, not at the element level.

Still we are getting the same. SO DEBUG.

Vizu.chowdary@gmail.com JSCRIPT - 154


Debugging, put a break-point needed. Here we are concerned to whether return statement is working or not.

Vizu.chowdary@gmail.com JSCRIPT - 155


I should say return

In this kind of function we should have type SUBMIT not BUTTON.


Difference between SUBMIT and BUTTON is, Button acts same as the just as button. When you specify as submit, a form
is getting submitted and you can click on ENTER button

Now it works.

Example ends here.

IMPORTANT POINT:
REGULAR EXPRESSION by which we can validate whether particular string contains dot (.) or comma (,) or special
characters in JQUERY

Vizu.chowdary@gmail.com JSCRIPT - 156


EXAMPLE:
REQUIREMENT:I have <div> and <script> is available, now our requirement create a button

Execute, we will get output.

Now I don’t want to create button in html, let’s do this in JSCRIPT


This is thing which we do in SAP UI5.

Vizu.chowdary@gmail.com JSCRIPT - 157


OUTPUT: BUTTON without TEXT
Now we need some text.
We have to create text node.

Output:

DEBUG and see

Vizu.chowdary@gmail.com JSCRIPT - 158


PRESS F12

1) Put Break-point and 2) click on Refresh

Vizu.chowdary@gmail.com JSCRIPT - 159


Vizu.chowdary@gmail.com JSCRIPT - 160
I want to see div.
So type div and press on enter

==================================================================================================
Result is below

Click on this everything clears


==================================================================================================

Next is input. So type input and see if any value exists

Type input and press enter

It is undefined now. Because this line is not executed.

Clear the console (click for clear console)

Vizu.chowdary@gmail.com JSCRIPT - 161


Let’s go to the step over. (Click)

Point of execution is at line number 16.

=================================================================================================

Now type input and press ENTER.

Vizu.chowdary@gmail.com JSCRIPT - 162


Input is just a button

=============================================================================================

STEP OVER

Now I am appending child to the text

It will not reflect immediately

Vizu.chowdary@gmail.com JSCRIPT - 163


Even if you put cursor on your input, you will be able to see lot of stuff(child node, txt, node value etc. give lot of
information.)

Now let’s test the input

Element Text Node Element

This is how console of developer tool helps.

Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx===We can do same at Mozilla also. === xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Vizu.chowdary@gmail.com JSCRIPT - 164


Now same above program.
Dynamically if we have to create input.
<input type = “button” class = “cls” value = “ok”/>
Here I am using class.
First there should be reference value

OUTPUT: execute this.

Vizu.chowdary@gmail.com JSCRIPT - 165


Same above program for multiple input

Give
Var txt1 = document.createTextNode(“click me”);

Assignment:
Create a table using JSCRIPT. It should be division <div> and content. ,<div id = “content”> </div>-

SAP JAVA
.NET PHP
First display the table
Add text - button
Delete - table
Update table – text type, input type

Vizu.chowdary@gmail.com JSCRIPT - 166


EXAMPLE: same above program using style for button (HTML LEVEL)

Vizu.chowdary@gmail.com JSCRIPT - 167


EXAMPLE: same above program using style for button (JSCRIPT LEVEL)

Using setAttribute, we can set ID also.

IMPORTANT NOTE:
Still now we created an element, read the element values, setAttribute(will return values), Modified text.

NOW LET’s WORK ON DELETE.

Vizu.chowdary@gmail.com JSCRIPT - 168


EXAMPLE:
All are global variables

OUTPUT:
click on this ----

it will be deleted. These all are called as CRUID methods in SAP UI5

Vizu.chowdary@gmail.com JSCRIPT - 169


SESSION – 3

CAN I CREATE THIS FORM USING JAVASCRIPT?


YES.

Vizu.chowdary@gmail.com JSCRIPT - 170


Debugger is a keyword like BREAK-POINT in ABAP

Execute
PRESS F12

The keyword debugger will not work for us.

Click on REFRESH

Vizu.chowdary@gmail.com JSCRIPT - 171


Function is not yet called.

So let’s load the function.

Vizu.chowdary@gmail.com JSCRIPT - 172


PRESS F12
Click on refresh
Now debugger is pointing

Click on step over.

GOT EXECUTED, but output is nothing.

Vizu.chowdary@gmail.com JSCRIPT - 173


Use console.log

Vizu.chowdary@gmail.com JSCRIPT - 174


In the Developer tool,
Console.log is available

Click on STEPOVER.

Vizu.chowdary@gmail.com JSCRIPT - 175


Try to observe here. {console.log(label);} and step over.

The object is label

After executing, output would be nothing.

Vizu.chowdary@gmail.com JSCRIPT - 176


So
Now the text node should be appended to the label.

Vizu.chowdary@gmail.com JSCRIPT - 177


PRESS F12
Click on Refresh
STEP OVER

ONCE I EXECUTE, CAN I EXPECT A LABEL?


No.
We have created the label. Label is available to us.
We have to place the label.

It should be child of <div>. It should refer where to be placed.

The relation between <div> and <label> here is Parent and Child.

Vizu.chowdary@gmail.com JSCRIPT - 178


STEPS:
1. First I have take the reference of the division. There are many ways, but in ui5 we use like this.
2. Write id = content.
3. Append child

OUTPUT:

Explanation for above program


STEP1: taken the reference of division as div.
STEP2: created as element label.
STEP3: Created a text node with name EMPLOYEE NAME*
STEP4: we created a relationship between label and text node. Added text node to label as a child. Label is available for
us. It should be placed.
STEP5: is to place label, we have used div as a reference and added label to div as a child Element.

Vizu.chowdary@gmail.com JSCRIPT - 179


VERY VERY IMPORTANT POINT:

Here we can give any name (variable)


Here we can give only ELEMENT which is html element – i.e. createElement

Here we can give any name, this is not any element.


NEXT TASK IS ADD INPUT TEXT

Vizu.chowdary@gmail.com JSCRIPT - 180


EXECUTE. PRESS F12. Press on REFRESH button.

Press on STEP OVER.

Now INPUT is available.

In output it will not show, because we haven’t added to the div. so let’s add it now.

Vizu.chowdary@gmail.com JSCRIPT - 181


It’s available to us now.

OUTPUT:

By default input takes type as TEXT.

For input we need to SET ATTRIBUTE as well

Vizu.chowdary@gmail.com JSCRIPT - 182


Vizu.chowdary@gmail.com JSCRIPT - 183
I want use color for label (Attributes are already available, we are setting it.)

Vizu.chowdary@gmail.com JSCRIPT - 184


Do the remaining things, should be done with JSCRIPT.

DOES IT MAKE ANY SENSE CREATING ELEMENTS IN JAVASCRIPT?


 Dynamic screening. We can manipulate at run time.
 Re-usability.

END OF
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXEMPLOYEE FILED USING JAVASCRIPTXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Vizu.chowdary@gmail.com JSCRIPT - 185


REGULAR
EXPRESSIONS

Vizu.chowdary@gmail.com JSCRIPT - 186


REGULAR EXPRESSIONS

I have to validate user naming. Somebody writes the numeric which is not allowed.

E.g.
Pattern used by user for street is

Street: 123 main street.

How to validate this.

If user would validate with alpha, then numeric should not allow end user to do that.

Regular expression for this is /\d{1,5}\s\w+\s\w+\./

Vizu.chowdary@gmail.com JSCRIPT - 187


OUTPUT:

1:10

How to design the pattern?

Street pattern: 123 main st.

First pattern is 123 (3 digits)

/ - expression always starts and ends with /

123 are digits

\d (d should be small letter for digit)

\D (D should be capital letter for not digit)

\d{3}

\d{1,3}- (if I specify {1, 3} = there can be minimum 1 and maximum 3 digits)

Vizu.chowdary@gmail.com JSCRIPT - 188


Second pattern is space

\s (s should be lower letter for space)

\S (S should be Capital letter for not space)

THIRD pattern is word character

\w – stands for single character


\w+ - least 1 character to n characters

Fourth pattern is word character

\w+ - least 1 character to n characters

Finally \.

Output is

/\d{1,3}\s\w+\s\w+\./

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

In the above program I am giving space then entering the value.


But it is showing as valid street number, where I am not happy with this.

For this what should we do?


Keep an exponential begining.
Keep $ ending.

/^\d{1,3}\s\w+\s\w+\.$/

Now it’s ok.

Vizu.chowdary@gmail.com JSCRIPT - 189


NOW WE NEED TO VALIDATE THIS FORM ON FIELDS LIKE EMAIL, PAN NUMBER (SSN –
social Security number - Canada)

Let’s go with email validation.

Email: info_a-director2.org@v-jay.in

Can start with capital letter, small letter and 0 – 9. My email id can also start with _ and -
It can contain .

^([A-Za-z0-9_\-\.]) {1,}

What should be the minimum length of it?


Minimum I am specifying 1 and maximum I am not giving. It can be any.

This is still info_a-director2.org

Next is @ = \@

^([A-Za-z0-9_\-\.]){1,}\@

Next is v-jay.in = ([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,3})

^([A-Za-z0-9_\-\.]){1,}\@([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,3})$

NOTE: always variable start with lower letter

emailCode: ^([A-Za-z0-9_\-\.]){1,}\@([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,3})$

Vizu.chowdary@gmail.com JSCRIPT - 190


EXAMPLE

Vizu.chowdary@gmail.com JSCRIPT - 191


Test cases:

(1) Valid

(2) invalid

(3) invalid

(4) valid

Vizu.chowdary@gmail.com JSCRIPT - 192


WHAT REGULAR EXPRESSION DOES?
A regular expression is an object that describes a pattern of characters.

BRACKETS:
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of
characters. (Or)
Brackets are used to find a range of characters:

Expression Description
[...] Any one character between the brackets.
[^...] Any one character not between the brackets.
[^abc] Find any characters NOT between the brackets (don’t allow those characters)
[0-9] It matches any decimal digit from 0 through 9.
Find any digit between the brackets.
[^0-9] Find any digit NOT between the brackets.
[a-z] It matches any character from lowercase a through lowercase z.
(or) Find any characters between a-z
[A-Z] It matches any character from uppercase A through uppercase Z.
(or) Find any characters between A-Z
[a-Z] It matches any character from lowercase a through uppercase Z.
[abc] Find any characters between the brackets

METACHARACTERS: Meta characters are characters with a special meaning:

Meta Description
character
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word
\B Find a match not at the beginning/end of a word
\0 Find a NUL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
\uxxxx Find the Unicode character specified by a hexadecimal number xxxx

Vizu.chowdary@gmail.com JSCRIPT - 193


QUANTIFIIERS:
The frequency or position of bracketed character sequences and single characters can be denoted by a special character.
Each special character having a specific connotation. The +, *, ?, and $ flags all follow a character sequence.
Expression Description
p+ It matches any string containing at least one p.
p* It matches any string containing zero or more p's.
p? It matches any string containing one or more p's.
p{N} It matches any string containing a sequence of N p's
p{2,3} It matches any string containing a sequence of two or three p's.
p{2, } It matches any string containing a sequence of at least two p's.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.

Vizu.chowdary@gmail.com JSCRIPT - 194


Vizu.chowdary@gmail.com JSCRIPT - 195
OOPS IN JAVASCRIPT:
What is the usage of Object Oriented Program?
Re-usability – extendibility (inherited)

OUTPUT:

EXAMPLE

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 196


Explanation: defining PROPERTIES FOR AN OBJECT

document is an object. getElementById is an method. value is property

Before we were using


document.write() – these are in-built pre-defined objects provided at JS level.

Vizu.chowdary@gmail.com JSCRIPT - 197


Explanation: defining FUNCTION FOR AN OBJECT
Object contains function as well.

Property

Object name function name (method name)

Vizu.chowdary@gmail.com JSCRIPT - 198


ROLE OF A FUNCTION IN AN OBJECT
CHARACTERISTIC: Execute series of statements
PURPOSE: avoid less coding. Uses properties & manipulate property values

Initial I gave vejaykumaar b, but getName has changed value from vejaykumaar b to BVK

Vizu.chowdary@gmail.com JSCRIPT - 199


In above program we had given getName, but it should be setname

The above program can be done pretty easily.

Vizu.chowdary@gmail.com JSCRIPT - 200


We can remove ( ) and use { }

Old way of designing of methods

This pattern is called as object literals. People are using this

New way of designing methods


Address (child object) is an object in object of employee (parent object)
The relation between employee and address is COMPOSITION. Employee object is composed of Address object
An object can contain other object (inner object). without employee we cannot access address

Vizu.chowdary@gmail.com JSCRIPT - 201


ACCESSING

Vizu.chowdary@gmail.com JSCRIPT - 202


Accessing inner object

This is how we declare objects.


The role of the methods & properties of object.

Vizu.chowdary@gmail.com JSCRIPT - 203


Manipulating

Vizu.chowdary@gmail.com JSCRIPT - 204


JAVASCRIPT
PROTOTYPE

Vizu.chowdary@gmail.com JSCRIPT - 205


JAVA SCRIPT PROTOTYPE
SESSION - 4

WHAT IS PROTOTYPE? SIGNIFICANCE?

Used as part of inheritance.

 JavaScript has inheritance concept.


 This will be used whether JS guys, they have their own objects and we can use them / we can inherit them.
 When it comes to SAP UI5, have predefined objects like BUTTON, TABLE, PARA, DIV, HYPERLINK, TEXT, INPUT
and so on. What we need to do is we need to reuse the code provided by SAP UI5. Whenever required we
rewrite the code. For e.g. SAP has given a button as name TEXT: BUTTON, but in our real time we may
requirement like as TEXT of BUTTON as ACCEPT or REJECT or CLICK. In this scenarios we need override the
existing text of a button. This is what we regularly practicing in UI5. Because they have given pre-defined UI
elements to us.

 All JavaScript objects inherit the properties and methods from their prototype.
 Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.
 Objects created with new Date() inherit the Date.prototype.
 The Object.prototype is on the top of the prototype chain.
 All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.

WHY / HOW PROTOTYPE? OR WHY WE HAVE TO INHERIT THE EXISTENCE OBJECT?


 Reusability through inheritance.

HOW TO CREATE A PROTOTYPE?


POINT: The standard way to create an OBJECT PROTOTYPE is to use an OBJECT CONSTRUCTOR FUNCTION.
Explanation: We have to use a function, that will be constructor and finally that will become an object prototype.
Prototype start with function creating prototype of function object

Vizu.chowdary@gmail.com JSCRIPT - 206


This is the prototype, already defined by some consultant

We want to use this at our side

Where I had defined the variables, values I had defined in PERSON


JS interpreter takes PERSON as PROTOTYPE.
When I assign it to the Emp1 and when I say new person, the object is created as Emp1

Vizu.chowdary@gmail.com JSCRIPT - 207


Go to the console and type Emp1. It shows this object (Emp1) contains
Emp1 Prototype object is person. It got inherited from the person and values are as below

------------------------------------------------------------------------------------------------------------------------------------------------------
Similarly I can create one more EMP2

PROTOTYPE is like a CONSTRUCTOR. That is what the point we discussed above (POINT: The standard way to create an
OBJECT PROTOTYPE is to use an OBJECT CONSTRUCTOR FUNCTION.
)

This is normal function


When we define Emp1 = new person. JS considers this as a constructor of type object person
The definition inside function can be inherited.
We can create 100 Emp

Vizu.chowdary@gmail.com JSCRIPT - 208


In real time, this function is controlled at (. JS file) & it can be defined by one of our mate (senior developer)
Similar in SAP UI5 also.

And we use here

Vizu.chowdary@gmail.com JSCRIPT - 209


CAN WE HAVE METHODS AND EVENTS IN PROTOTYPE?
Yes, we can define both inside prototype

This – belongs to object person

Vizu.chowdary@gmail.com JSCRIPT - 210


Type Empl1 and press ENTER

expand

This is the same what we use in SAP UI5

NOTE: The prototype inherits.

Vizu.chowdary@gmail.com JSCRIPT - 211


SIMPLE EXAMPLE IN REAL TIME.
SAP has given firstname, lastname, age, eye

Now I would like add a new property to it.


So I can add a property for the function like
person.prototype.employeeId = ‘ SAP2302‘

For the prototype I am adding a new property/new variable/new attribute to existing this person

We have added a new property employeeId, will it be inherited in Emp1 or not?


YES.

Vizu.chowdary@gmail.com JSCRIPT - 212


If I write as function person
Directly with prototype we cannot use.
The prototype is used when it got inherited

Console: Shows as un-defined.

Prototype are the abstract objects which can be used by referring to some third parties

Vizu.chowdary@gmail.com JSCRIPT - 213


Same the above another way is

In real time we use as


Server details
Back-end connectivity
Hardcoded values
Naming convention we use is common.js in SAPUI5

Vizu.chowdary@gmail.com JSCRIPT - 214


HOW TO PASS THE VALUE TO THE DEFINED PROTOTYPE?
Follow above example.

WHAT IS PROTOTYPE?
Prototype is an object. Which cannot be used directly, but can be referred.

Here, person.prototype is an object and we are referring to attribute employeeId.

Prototype is a constructor.
Constructor accepts the initialized values.

Vizu.chowdary@gmail.com JSCRIPT - 215


EXAMPLE:
Prototype is defined in the form of FUNCTION, FUNCTION_NAME, AND ARGUMENTS (PASS IT FROM 3RD PARTIES)

Those will be inherited to Emp1 and Emp2

One way of defining variable


Adding property to an object prototype, that can be done by using peson.prototype.employeeName = ‘SAP2302’
OR

Vizu.chowdary@gmail.com JSCRIPT - 216


person.prototype.getName = function(){
return (this.firstname + “ “ + this.lastname).
}

Vizu.chowdary@gmail.com JSCRIPT - 217


CAN WE CHECK SYNTACTICAL ERRORS IN JAVA SCRIPT? HOW TO ENSURE THAT OUR PROGRAM IS SYNTACTICALLY
CORRECT?
Notepad++ is not going to help us, whether syntactically written or not.
But we have inbuilt IDE’s, there are so many IDE’s. check them in Google.

WEBSORM is one among them.


There is help from Eclipse. But eclipse not completely.

Vizu.chowdary@gmail.com JSCRIPT - 218


INTRODUCTION TO JQUERY
JQUERY was developed in 2008 by JOHN RESIG.

JQUERY is JavaScript library. JQUERY IS a package of JavaScript.

USAGE:
Easy way to add effects (animation effects).

BENEFITS:
- Fast loading library.
- Cross browser compatibility: when we use JAVASCRIPT, some fonts look huge and some effects are not
compatible with other browsers. These type of issues we may get when we use JAVASCRIPT. When we use
JQUERY most of the browser compatibility issues are resolved.
- Easy Ajax implementation. (AJAX – Asynchronous Java Script as XML.) {AJAX is JAVASCRIPT CODE}

ASYNCHRONOUS: without user’s permission, it is going to the back-end server, goes to application server, retrieves,
and validates whatever.

What happens with AJAX is, without user event (permission) we can send request to the back-end and we can
retrieve the data.

When I mouse over on stars, goes back and fetches the data.

Vizu.chowdary@gmail.com JSCRIPT - 219


WHY DO WE USE IT?
To add nice look and feel.

DOWNLOAD:
JQUERY library from jquery.com – show how to download and placing JQUERY.
Jquery is bundle of pre-defined functions and the objects of JAVASCRIPT. So we need to download that.
Click on download

Both versions – compressed and uncompressed versions are there.

Compressed version we cannot see the complete code.

So, got to uncompressed version

Vizu.chowdary@gmail.com JSCRIPT - 220


This is downloaded file.
This is with .js extension. Hence this is JavaScript file.

Open it will notepad++

This is complete JSCRIPT code.

PRE-REQUISITE TO WORK ON JQUERY:


HTML
JAVASCRIPT

WHAT IS BETWEEN # AND . (DOT) SYMBOL IN CSS?

Using ID

Id, class and name are attributes

# stands for ID and . Stands for class of HTML attribute (id, class, name)

Vizu.chowdary@gmail.com JSCRIPT - 221


Using class

Here name does not have any significance


Now we are going to use this style format in our JQUERY as well.

WHAT IS THE SIGNIFICANCE OF NAME?

INPUT is an element.
TYPE gives us what type of UI element we want to display (i.e. input field).
SIGNIFICANCE OF ID HERE (one usage is css – we can put background color, second usage is - we are fetching the value
in JAVASCRIPT)
SIGNIFICANCE OF CLASS (only for css - style)
SIGNIFICANCE OF NAME (name for JavaScript [works at client side] + Server Side Program)

Vizu.chowdary@gmail.com JSCRIPT - 222


PRESS ENTER

This is specified by Name

In JavaScript, instead of ID, I can use getElementByName() as well.

At same time server has to grab the detail


getParameter(); -------------- username is the parameter name--- getParameter(username);

Vizu.chowdary@gmail.com JSCRIPT - 223


EXAMPLE:

Click on

Vizu.chowdary@gmail.com JSCRIPT - 224


EXAMPLE: HIDE ME ON CLICK

Double click on this, it will be hidden.

Vizu.chowdary@gmail.com JSCRIPT - 225


EXAMPLE: THE SAME ABOVE EXAMPLE I WILL LOAD JQUERY

NOTE: Keep Jquery file which we downloaded and our html file in same folder.

$ stands for JQUERY This refers to own element para

Hide is a method
This is selector can be id / class / para. ($(p).hide())

What we done here, we have writing single line of code, instead of JAVASCRIPT multiple lines.

Execute.

Vizu.chowdary@gmail.com JSCRIPT - 226


HOW CAN I FIND FUNCTION OF JQUERY?

Goto JQUERY.COM

Click on API Documentation

Search for HIDE

Click on this

Vizu.chowdary@gmail.com JSCRIPT - 227


EXAMPLE: APPLY ON CSS
All files in a single folder.

$-Jquery ( ) Selector (whether I am going to use ID / CLASS/ element) EVENT

Onclick which should happen

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 228


EXAMPLE: Instead of p we can use ID
Can I apply to very specific based on the ID. Yes it can be done.

Click on this. Hidden

Remaining will not be hidden.

Vizu.chowdary@gmail.com JSCRIPT - 229


EXAMPLE: By default if we want to hide. On load we don’t want to display.

OUTPUT:

Vizu.chowdary@gmail.com JSCRIPT - 230


EXAMPLE:

OUTPUT:

Let me increase width and height

Vizu.chowdary@gmail.com JSCRIPT - 231


EXAMPLE: same above program

Now I am applying a java script here


Iframe load when it gets completed loaded then alert me.

Vizu.chowdary@gmail.com JSCRIPT - 232


WHAT IS THE DIFFERENCE BETWEEN READY AND LOAD?

In the program we used,


When the document is ready, get faded
When complete page gets loaded, then only it shows.

READY: before appears on the web page. When it gets ready then what ever the stuff we want to make we can write
inside *$(‘myPara’).fadeIn(4000)+

LOADED: when page is completely loaded

NOTE:
YOUTUBE
Jquery tutorials for beginners quenton

Vizu.chowdary@gmail.com JSCRIPT - 233


SESSION - 5

Whatever the possibilities are there with JQUERY are possible with JAVASCRIPT
Whatever the functionality that JQUERY has, it is pretty much possible with JAVASCRIPT as well.

WE CAN VALIDATE INPUT FIELD USING JQUERY. WHICH IS ALSO POSSIBLE WITH JSCRIPT. WHY SO?
JQUERY is built over JSCRIPT to reduce the complexity.

 JQUERY is inner built using JAVASCRIPT. So whatever possibilities are there with JQUERY, pretty much possible
with JSCRIPT. BUT NOT VICE VERSA.
 One of the limitation that I had observed is, cannot create element using JQUERY.
 JQUERY USES DIFFERENT OPERATION LIKE IF, WHILE, DOWHILE, FOR LOOP.

 If we don’t know JAVASCRIPT, we can work on JQUERY. One or someday we need to compare JSCRIPT. Because
JQUERY is not fully replacement of JavaScript.
 With the help of JQUERY we are minimizing code and we are making whatever the stuff that is the cross browser
compatibility.

HIDING A PARA

jQuery() – function Event what should happen, I will write inside function
on which part
I need to click (on para)

On click of that what should happen (should hide). Which element should hide is para
OUTPUT:
Click on this

It will get hided.

Vizu.chowdary@gmail.com JSCRIPT - 234


EXAMPLE: simple modification to above program

OUTPUT:

Click anywhere of para.

It will hide whole part.

Vizu.chowdary@gmail.com JSCRIPT - 235


EXAMPLE: To above program, I need to hide, only which I click on. Not others.

OUTPUT:

Click on this

Only that will be hided

Vizu.chowdary@gmail.com JSCRIPT - 236


EXAMPLE: To above program, when I click on respective para only that para has to get hidden.

On all the para’s

Find on which element, we have done click, that to hide.


This transfers the current para, which we clicked.

OUTPUT:

Click on para 5 – para 5 will be hidden

Click on para 9 – para 9 will be hidden

And so on………………

Vizu.chowdary@gmail.com JSCRIPT - 237


REQUIREMENT 1: I have 3 buttons. Login-1(button), Login-2(button), Login-3(submit).
Clicking on any button should alert me a message ‘hello’.

I can write direct html element name in JQUERY

OUTPUT: click on any button

Vizu.chowdary@gmail.com JSCRIPT - 238


REQUIREMENT 2: I have 3 buttons. Login-1(button), Login-2(button), Login-3(submit).
When I click on button, then alert me message, not on submit button

Same as above

Colon and type (button)

OUTPUT:
When you click on LOGIN-1 and LOGIN-2 you will get alert message.

When you click on LOGIN-3, we won’t get alert message.

Vizu.chowdary@gmail.com JSCRIPT - 239


REQUIREMENT 3: I have 3 buttons. Login-1(button), Login-2(button), Login-3(submit).
When I click on submit (Login-3), the content should change from Login-3 to Please wait.

WHAT IS INNER HTML?


<p> this is inner html content </p>
Between the tags, we have text that is called as INNER HTML.

Instead of jQuery I can use $ symbol

Key value

I can write submit as well in place of this

OUTPUT: click on Login-3

Vizu.chowdary@gmail.com JSCRIPT - 240


REQUIREMENT 4: I have 3 buttons. Login-1(button), Login-2(button), Login-3(submit).
If I click on any button, that button should change as please wait

OUTPUT:

Click Click Click


Changes Changes Changes

Vizu.chowdary@gmail.com JSCRIPT - 241


REQUIREMENT 4: I have 3 buttons. Login-1(button), Login-2(button), Login-3(submit).
When I click on particular button, it should be yellow.

OUTPUT:

Click Click Click


Changes Changes Changes

Vizu.chowdary@gmail.com JSCRIPT - 242


ASSIGNMENT:

I have two texts

OUTPUT:

Place cursor, it turns to yellow.

When I click on LOGIN-2, LOGIN-1 has to be disabled / LOGIN-1 has to become white color.

QUESTIONS:

What is $(this) stands for?


Selects the current element.

What is $(“div”) stands for?


Selects all the div elements on the page.

What is $(“div p”) stands for?


Selects all the p elements that are directly inside div elements.

What is $(“.my_class”) stands for?


Selects all the elements with the my_class Class attribute

What is $(“div.my_class”) stands for?


Selects only the divs that have the my_class as a class attribute. (Different types of elements can share a class)

What is $(“#my_id”) stands for?


Selects the element that has the ID of my_id.

Vizu.chowdary@gmail.com JSCRIPT - 243


ANIMATIONS OF JQUERY

OUTPUT: when I click on image, it gets hide.

Vizu.chowdary@gmail.com JSCRIPT - 244


OUTPUT: execute & click on the image. Disappears.

We can also specify fast


OUTPUT: execute & click on the image. Slowly disappears.

OUTPUT: execute & click on the image. Disappears after some time too slowly.

OUTPUT: execute & click on the image. Disappears after some time too slowly and comes back to visible.

Vizu.chowdary@gmail.com JSCRIPT - 245


NOTE:
For all these kind of functions go to the JQUERY.COM -> API DOCUMENTATION and search there

Click on

Vizu.chowdary@gmail.com JSCRIPT - 246


We can write
Another function
Complete

Scroll down this page you will get examples

Still scroll down. Some information u can get.

Vizu.chowdary@gmail.com JSCRIPT - 247


OUTPUT:

Click on this. Slowly faded and gives as

Vizu.chowdary@gmail.com JSCRIPT - 248


0 to 0.5 opacity

OUTPUT:

After clicking on image -----------

Vizu.chowdary@gmail.com JSCRIPT - 249


1) TOGGLE

Execute and see this

Execute and press F12

Vizu.chowdary@gmail.com JSCRIPT - 250


Click on refresh

Now click on image button

Jquery is working on DOM and that particular element.


Using Jquery function, Code is being applied in the back-end.
This we can do in JSCRIPT. But lot of stuff like for loop has to be done. But easy in JQUERY.

Vizu.chowdary@gmail.com JSCRIPT - 251


2) SLIDE TOGGLE

EXECUTE AND SEE

3) SLIDEUP

EXECUTE AND SEE

EXECUTE AND SEE


Press on F12 and see in debugging.

4) WIDTH IS 30% OF DOM WIDTH (SCREEN WIDTH). SHOW IT BEFORE 25 SECONDS

5) PADDING OF 200PX

There is padding of 200 px. It adjust in such way that top 200px and side 200px and all sides.

Vizu.chowdary@gmail.com JSCRIPT - 252


ASSIGNMENT:

REQUIREMENT: EMPLOYEE FORM IS AVAILABLE. UNDERNEATH SHOULD BE HIDDEN BY DEFAULT.


WHEN I SAY REGISTER THEN ONLY underneath should be visible.

It should move to the next level.

Vizu.chowdary@gmail.com JSCRIPT - 253


EXAMPLE: How can I find the length of the para?

Vizu.chowdary@gmail.com JSCRIPT - 254


JQUERY: this is the query function, whose whole job is grabbing the elements out into the parenthesis.

$(shortcut) to JQUERY.

WHAT WE CAN DO WITH IN JQUERY FUNCTION?

Add up HTML Element


$(‘P’)
$(‘div’)
$(‘input’)
CSS Selector
$(‘.paraClass’)
$(‘#paraID’)

What is $(this)?
‘this’ stands for referring element on which event is triggered.

WORKING with SELECTORS?


For all paragraph only,
For all selector (*). Asterisk refers to all elements.
- Number of element html

ELEMENT SELECTORS?
HTML Element level
How to select particular element.

<input type = “text” id = “nameID” class = “nameClass” name = username />


What is the significance of type here?

I can specify it as input field, check box (type = “checkbox”), radio button (type = “radiobutton”).
I can specify type, where user can input.

What is the significance of ID (id = “nameID”)


It is used to select or call the element in JAVASCRIPT.
For us this ID can be used for JAVASCRIPT (getElementById)
CSS styling. (based on Id, I can specify the background color)
ID is used in JQUERY. ID can be applied to only UI element of DOM / HTML ELEMENT (unique)

What is the significance of Class (class = “nameClass”)


Class attribute: can be used for styling of group of elements.
Class we can apply for group of elements, whereas Id we cannot apply for group of elements.

WHAT IS THE SIGNIFICANCE OF NAME (name = “nameName”)?


Used especially for the input element and for the form.
Use it in javascript (getElementByName)
Server side program can grab the value of this element (HTML - get/post).
We already seen an example on this.

==============================THE END==============================

Vizu.chowdary@gmail.com JSCRIPT - 255


Vizu.chowdary@gmail.com JSCRIPT - 256
JAVASCRIPT PAGE REDIRECT

What is page redirection ?

When you click a URL to reach to a page X but internally you are directed to another page Y that simply happens because
of page re-direction. This concept is different from JavaScript Page Refresh.
There could be various reasons why you would like to redirect from original page. I'm listing down few of the reasons:
 You did not like the name of your domain and you are moving to a new one. Same time you want to direct your
all visitors to new site. In such case you can maintain your old domain but put a single page with a page re-
direction so that your all old domain visitors can come to your new domain.
 You have build-up various pages based on browser versions or their names or may be based on different
countries, then instead of using your server side page redirection you can use client side page redirection to land
your users on appropriate page.
 The Search Engines may have already indexed your pages. But while moving to another domain then you would
not like to lose your visitors coming through search engines. So you can use client side page redirection. But
keep in mind this should not be done to make search engine a fool otherwise this could get your web site
banned.

How Page Re-direction works ?

Example 1:

This is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you
just need to add a line in your head section as follows:

Vizu.chowdary@gmail.com JSCRIPT - 257


Example 2:

You can show an appropriate message to your site visitors before redirecting them to a new page. This would need a bit
time delay to load a new page. Following is the simple example to implement the same:

Here setTimeout() is a built-in JavaScript function which can be used to execute another function
after a given time interval.

Example 3:
Following is the example to redirect site visitors on different pages based on their browsers :

Vizu.chowdary@gmail.com JSCRIPT - 258


Vizu.chowdary@gmail.com JSCRIPT - 259
JAVASCRIPT VIOD KEYWORD

The void is an important keyword in JavaScript which can be used as a unary operator that appears before its
single operand, which may be of any type.
This operator specifies an expression to be evaluated without returning a value. Its syntax could be one of the
following:

<head>
<script type="text/javascript">
<!--
void func()
javascript:void func()

or:

void(func())
javascript:void(func())
//-->
</script>
</head>

Example 1:
 The most common use for this operator is in a client-side javascript: URL, where it allows you to evaluate an
expression for its side effects without the browser displaying the value of the evaluated expression.
 Here the expression alert('Warning!!!') is evaluated but it is not loaded back into the current document:

<html>
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<p>Click the following link to see the result: </p>
<a href="javascript:void(alert('Warning!!!'))">Click me!</a>
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 260


Example 2:
Another example the following link does nothing because the expression "0" has no effect in JavaScript. Here the
expression "0" is evaluated but it is not loaded back into the current document:

<html>
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<p>Click the following, This won't react at all...</p>
<a href="javascript:void(alert(0))">Click me!</a>
</body>
</html>

Example 3:
Another use for void is to purposely generate the undefined value as follows:

<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
var a,b,c;

a = void ( b = 5, c = 7 );
document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</body>
</html>

Vizu.chowdary@gmail.com JSCRIPT - 261


Vizu.chowdary@gmail.com JSCRIPT - 262
REFERENCING ELEMENTS IN JAVASCRIPT
• getElementByID();
If we have referred a document, how we do that

PROGRAM:

Can I capture this content in our JSCRIPT?


Yes.

We can refer to this using an ID.


Using ID JAVASCRIPT visualizes / recognizes.

Vizu.chowdary@gmail.com JSCRIPT - 263


document is inbuilt class of java script, have the method of getElementById();

Output:

Output:

Note: alert will not work over here. It has to be enclosed with in the function.

Vizu.chowdary@gmail.com JSCRIPT - 264


PROGRAM:

Output: click on this

Vizu.chowdary@gmail.com JSCRIPT - 265


PROGRAM:

Output:
Click on this

Vizu.chowdary@gmail.com JSCRIPT - 266


PROGRAM:

OUTPUT:
Input some value in to this

Press on done

Vizu.chowdary@gmail.com JSCRIPT - 267


ASSIGNMENT: Validate username and password.

This is the script, validate user name and password here in jscript.

Output:

When we click on login. It has to navigate to your built application calculator

1) USERNAME & PASSWORD VALIDATION. – PASSED (SUCCESS) – NAVIGATE TO CALUCULATOR


2) ONLY USERNAME IS NOT VALIDATED (ERROR) – NEED TO GO TO REGISTRATION PAGE WHERE WE HAVE
REGISTRATION FORM.
3) ONLY PASSWORD FAILS FOR 5 TIMES………LOCK IT FOR 5 OR 25 MINUTES. THEN ALLOW TO LOGIN.

Vizu.chowdary@gmail.com JSCRIPT - 268


JAVA SCRIPT OBJECT DECLARATION

WHAT IS AN OBJECT ORIENTED PROGRAMMING?


You can compare it with the real time entities. However we behave.
Behavior – methods / functions
Properties – whatever we look like.

ADVANTAGE IS RE-USABILITY.

OBJECT = PROPERTIES + METHODS


Object has Properties. Properties are variables. And those variables are manipulated easily under methods.
The motto of the method is to manipulate properties of an object.

Properties are the values that object has, just as we have like height, complex etc.,
The way that properties reacts based on methods.

Object provides services to us.


Object provides business data to us.

Coding pretty easier than procedural language. Easily extendable as we have inheritance.

HOW TO CREATE AN OBJECT IN JAVASCRIPT?

var Person = new Object();

Here P is capital and O is capital

Vizu.chowdary@gmail.com JSCRIPT - 269


First name & last name are the property (properties).

Object reference should be lower letter.

OLD WAY:

The functionality of methods is to manipulate the properties of an object.

We have to call with object reference

Explanation of above program……………………….

Vizu.chowdary@gmail.com JSCRIPT - 270


PERSON
(is a variable which holds the address of the object) OBJECT

When we say NEW, a memory will be allocated. And that address is referred to person.
Person actual contains the address.
Person is not an object. It is an object reference.

TELL ME HOW MANY OBJECTS ARE CREATED?

Two objects are created and two references are created. They are not co-related to each other.

HOW MANY OBJECTS ARE CREATED?

Two objects are created and two references are created. They are co-related to each other

Vizu.chowdary@gmail.com JSCRIPT - 271


PROGRAM:

In flower braces { and }, we should not use ;


We can use ,

Execute

Vizu.chowdary@gmail.com JSCRIPT - 272


Next is java_object folder – batch 1

Vizu.chowdary@gmail.com JSCRIPT - 273


ARRAYS

PROGRAM – 9

OUTPUT:

PROGRAM – 10: SINGLE DIMENSION ARRAY

Vizu.chowdary@gmail.com JSCRIPT - 274


Number of rows
Output:

Output:

Output:

Output:

PROGRAM – 11:

Vizu.chowdary@gmail.com JSCRIPT - 275


OUTPUT:

Here we are getting values (how many variables are there. It’s totally 4. )

Just go with w3schools for remaining.

Vizu.chowdary@gmail.com JSCRIPT - 276

You might also like