0% found this document useful (0 votes)
129 views211 pages

Web Framework 1 PDF

The document discusses web frameworks. A web framework is software that provides a foundation for developing dynamic web applications and minimizes overhead. Frameworks provide pre-written code for common tasks like user authentication. Many frameworks follow the Model-View-Controller pattern which separates an application into three parts: the model (data), view (UI), and controller (logic). Popular frameworks include Java-based like Spring and PHP-based like Laravel. Frameworks allow for faster development and robust applications.

Uploaded by

Sunil Shedge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views211 pages

Web Framework 1 PDF

The document discusses web frameworks. A web framework is software that provides a foundation for developing dynamic web applications and minimizes overhead. Frameworks provide pre-written code for common tasks like user authentication. Many frameworks follow the Model-View-Controller pattern which separates an application into three parts: the model (data), view (UI), and controller (logic). Popular frameworks include Java-based like Spring and PHP-based like Laravel. Frameworks allow for faster development and robust applications.

Uploaded by

Sunil Shedge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 211

WEB FRAMEWORK

What is framework?

➢ Web Framework is software designing platform which used


to develop the dynamic websites, web applications, web
services and web resources.
➢ The framework aimed to minimize the overhead
associated with common web development activities
➢ It is set of pre-written code or libraries which provide
functionality common to whole class of applications.
➢ The framework can be work as skeleton on which we
build our software.
➢ There exist dozens of application framework.
Why we need to use framework?

➢ Virtually all web applications have common set of basic


requirments like user management for e.g. secure user
login, password recovery etc., group management and
accesses authorization.
➢ Web framework usually includes all these
functionalities,refind through hundreds of deployments,
freeing developers to focus on needs of their specific
application.
➢ In high traffic web application like social sites, registration
sites etc.,web framework provides excellent support for
developing application having good traffic handling
capacity by applying pooling technique.
Model-View-Controller(MVC)

➢ Many frameworks follows the Model-View-Controller (MVC) design


pattern
➢ MVC is software architectural platform for implementing user
interfaces on computer.
➢ It divides specific application in 3 interconnected parts.
➢ It is done to separate internal representation of information from
way information presented to and accepted from user.
➢ The MVC designing pattern decouples these major components
allowing for efficient code reuse and parallel development
➢ MVC used to design desktop GUI,Web application and mobile
application
 Popular programming languages such as
C++,C#,Java,PHP,ruby and other have popular MVC
framework that are currently being used in web
development process
 Popular MVC framework that are currently being used in
web application development. Now see layers in MVC:
Model:In this layer we perform operation on database such as
update,insert and delete the data
View: In this layer we show end user GUI through which user
can interact with system i.e.HTML,CSS,javascript code.

Controller: This layer contains certain business logic and


provide link between Model and view layer .
➢ Leads to fast and robust software development
process
➢ Following are some famous web frameworks-
Java based frameworks:
PHP based framework
Syallabus
Topic No Name
1 Java Script Basics

1.1 Java Script data types


1.2 Variables, Functions, Events, Regular Expressions
1.3 Array and Objects in Java Script
1.4 Java Script HTML DOM
1.5 Promises and Callbacks
2 Introduction to Node JS

2.1 Introduction
2.2 What is Node JS and its advantages
2.3 Traditional Web Server Model
2.4 Node JS Process model
2.5 Installation of Node JS
2.6 Node JS event loop
3 Node JS Modules
3.1 Functions
3.2 Buffer
3.3 Module and Module Types
3.4 Core Module, Local Module
3.5 Directories as module
3.5 Module.exports
4 Node Package Manager
4.1 What is NPM?
4.2 Installing package locally
4.3 Adding dependencies in package.json
4.4 Installing packages globally
4.5 Updating packages
4.6 Managing Dependencies
5 Web Server
5.1 Creating Web Server
5.2 Handling HTTP requests
5.3 Sending Requests
5.4 HTTP Streaming
6. File System
6.1 FS Model
6.2 Files and Directories
6.6 Streams
6.4 Reading and Writing Files
6.5 Reading and Writing Directories
6.6 Other File Operations
7 Events
7.1 Asynchronous JS
7.2 Asynchronous control flow with
callbacks
7.3 Promises
7.4 EventEmitter Class
7.5 ASync/Await
7.6 Returning Event Emitter
7.7 Inheriting Events
8. Working with Databases

8.1 Connection String


8.2 Configuring
8.3 Working with Select command
8.4 Various database operations
8.5 MongoDB
8.6 Mongoose ODM
8.7 Mongoose Schema
8.8 Mongoose Model
8.9 Querying with Mongoose
9. Express JS
9.1 REST
9.2 Introduction to Express JS
9.3 Routing, Responding
9.4 Configuration
9.5 Views
9.6 Receiving Data
10. Introduction to DJango

10.1 What is DJango


10.2 DJango and Python
10.3 DJango MVT
10.4 How to get and install DJango
11 Getting Started with DJango

11.1 About 3 core files : model.py,


urls.py, views.py
11.2 Setting up database connections
(MySQL/SQLServer)
11.3 Managing Users & DJango admin
tools
11.4 Installing and using ‘Out of the
Box’ Django features
12. DJango URL Patterns and Views

12.1 Designing a good URL Schema


12.2 Generic Views
13 DJango Forms
13.1 Form Classes
13.2 Validations
13.3 Authentication
13.4 Advanced Form Processing
Techniques
13.5 DJango REST Framework
13.6 DJango Piston
Reference Books
1. Node.js complete reference guid , velentin Bojinov, David
Herron, Dioge Resende,packt Publishing Ltd
2. Mastering Nod.js By Sandro Pasquali , packt Publishing
3. Smashing Node.js, Java Script Everywhere , Guillermo
Rauch, John wiley & Sons
4. Django for Beginners : Build websites with Python and
Django Kindle Edition by William S Vincent
5. Two Scoops of Django 1.11 : Best Practices for the Django
web Framework Book by Danial Roy Greenfeld and Audrey
Roy Greenfeld
6. Web Development with Django CookBook by Aidas
Bendoraits Second Edition PACKT Publishing
What is JavaScript?

❖ JavaScript is a dynamic scripting language


❖ It is lightweight and most commonly used as a part of web
pages, whose implementations allow client-side script to
interact with the user and make dynamic pages.
❖ It is an interpreted programming language with object-
oriented capabilities.
i.e. it executed without preliminary compilation.
❖ It is designed to add interactivity to HTML pages
❖ Java and JavaScript are different
❖ We can use JavaScript with java also.
What can JavaScript do?

❖ JavaScript gives HTML designers a programming tool:


-simple syntax
❖ JavaScript can put dynamic text into an HTML page
❖ JavaScript can react to events
❖ JavaScript can read and write HTML elements
❖ JavaScript can be used to validate data
❖ JavaScript can be used to detect the visitor’s browser
❖ JavaScript can be used to create cookies
-Store and retrieve information on the visitor’s computer
How to use Javascript

 The HTML <script> tag is used to insert a JavaScript into


an HTML page
<script type=“text/javascript”>
document.write(“Hello World!”)
</script>
 Ending statements with a semicolon?
 Optional;required when you want to put multiple
statements on a single line
 JavaScript can be inserted within the head, the body, or use
external JavaScript file
Where we can use JavaScript?

 You can include JavaScripts in head, body, or simply use


external JavaScript file (.js)
 JavaScripts in the body section will be executed while the
page loads
 JavaScripts in the head section will be executed when
called
Variables in Javascript
 A variable is a name associated with a piece of data
 Variables allow you to store and manipulate data in your
programs
 Think of a variable as a mailbox which holds a specific
piece of information
 In JavaScript variables are created using the keyword var
 Example:
var x = 10;
var y = 17;
var color = “red”;
Datatypes in JavaScript

Data types

Primitive Composite
Data Types Data Types
Number Arrays

String Objects

Boolean(True,False)
Primitive Data Types

➢ Numbers - A number can be either an integer or a decimal


➢ Strings - A string is a sequence of letters or numbers
enclosed in single or double quotes
➢ Boolean - True or False
Variables & Data Types

 JavaScript is untyped; It does not have explicit data types


 For instance, there is no way to specify that a particular
variable represents an integer, string, or real number
 The same variable can have different data types in different
contexts
Type casting
➢ Casting is a process of changing one type value to another type.
➢ In Java, we can cast one type of value to another type. It is known as type
casting.
➢ For example
Int x=10;
Byte y=(byte)x;
➢ The conversion of a data type which is carried out automatically by the
compiler without programmer intervention is called the implicit type
conversion.
➢ When two variables of different data types are involved in the same
expression, the Java compiler uses built-in library functions to trans- form
the variables to common data type before evaluating the expression.
➢ To decide which variable's data type is to be converted, the Java compiler
follows certain rules.
-When we convert smaller type to larger type size is called as Widening Casting
-Which can be as
byte -> short -> char -> int -> long -> float -> double
-Widening casting is done automatically when passing a smaller size type to a
larger size type.
- When we convert larger type to smaller type size is called as Narrowing Casting
- Which can be as
double -> float -> long -> int -> char -> short -> byte
Variables, Functions, Events, Regular
Expressions
Variable
➢ It is name given to memory location
➢ Variables can be thought of as named containers.
➢ You can place data into these containers and then refer to the data simply by
naming the container.
➢ Before you use a variable in a JavaScript program, you must declare it. Variables
are declared with the var keyword as follows.

<script type = "text/javascript">


<!-- var money; var name; //-->
</script>

➢ Storing a value in a variable is called variable initialization. You can do variable


initialization at the time of variable creation or at a later point in time when you
need that variable.
JavaScript Variable Scope

 he scope of a variable is the region of your program in which it is defined.


JavaScript variables have only two scopes.
1.Global Variables − A global variable has global scope which means it can be
defined anywhere in your JavaScript code.
2.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.
 Take a look into the following example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!-- var myVar = "g
lobal"; // Declare a global variable function
checkscope( )
{ var myVar = "local"; // Declare a local
variable document.write(myVar); } //--> </script>
</body>
</html>
JavaScript Variable Naming rules

While naming your variables in JavaScript, keep the following rules in mind:
 You should not use any of the JavaScript reserved keywords as a variable
name. These keywords are mentioned in the next section. 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 an 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

A list of all the reserved words in JavaScript are given in the following
table. 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
Operator in Javascript

 Operand is input data on which we perform specific operation


 Operator is symbol which we applied on operand to perform specific
operation
 For example
2 + 5

Oprands Operator
➢ The list of operators is given below:
•Arithmetic Operators
•Relational Operators
•Bitwise Operators
•Logical Operators
•Assignment Operators
•String Operators
JavaScript Arithmetic Operators
 JavaScript Arithmetic operators are used to perform arithmetic operations
like addition, subtraction, multiplication, etc.
 All the arithmetic operators have been listed in the below table.
<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); //-->
</script> Set the variables to different values and then
try... </body>
</html>
JavaScript Relational Operators

 These operators are used to perform comparisons between two operands.


 We will use these operators when we will cover JavaScript if else Flow
Control.
<!-- var a = 10; var b = 20; 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) => ");
result = (a >= b);
document.write(result);
document.write(linebreak);
document.write("(a <= b) => ");
result = (a <= b);
document.write(result); document.write(linebreak); //--> </script> Set the
variables to different values and different operators and then try...
Output:

(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true Set the variables
to different values and different
operators and then try...
JavaScript Bitwise Operators

 Javascript bitwise operator perform operation on bit.


 Assume variable A =2 and B=3, then
<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);
document.write(result);
document.write(linebreak);
document.write("(a ^ b) => ");
result = (a ^ b);
document.write(result);
document.write(linebreak)
document.write("(~b) => ");
result = (~b);
document.write(result);
document.write(linebre
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>
JavaScript Logical Operators

The logical gate's functions are used as logical operators in JavaScript. These
operators are also used in Flow control.
JavaScript Assignment Operators
 These are the operators used while assigning the values to the variables.
Conditional Operator (? :)

The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.

Sr.No. Operator and Description

1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
Flow Control statements in java

 While writing a program, there may be a situation when you need to adopt
one out of a given set of paths.
 In such cases, you need to use 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.
If-else conditional statement
 Syntax-

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

<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>
if...else if... statement

The if...else if... statement is an advanced form of if…else that allows


JavaScript to make a correct decision out of several conditions.
Syntax:
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
}
Example

<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>
Output:
Maths Book Set the variable to
different value and then try...
JavaScript Switch

➢ The switch is a conditional statement like if statement.


➢ Switch is useful when you want to execute one of the multiple code blocks
based on the return value of a specified expression.
➢ Syntax
switch(expression or literal value)
{ case 1: //code to be executed break;
case 2: //code to be executed break;
case n: //code to be executed break;

default: //default code to be executed //if none of the above case executed }
 switch statement contains a literal value as expression. So, the case that
matches a literal value will be executed
 The value of the expression is compared with the values of each case.If there
is a match, the associated block of code is executed.If there is no match, the
default code block is executed.
 This expression may be string or number
 The break statements indicate the end of a particular case. If they were
omitted, the interpreter would continue executing each statement in each of
the following cases.
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Loops in JavaScript
➢ There are times when we would want to perform a certain operation a
certain number of times, like if we have a list of employees with their
salaries and we have to calculate their income tax. Now the formula
for getting the income tax is the same for all employees, so we can
have a loop and execute the code statements with different inputs.
➢ Similarly, for a use case like printing the mathematical table of a
number like 2, we can simply have a loop in place to keep on
multiplying the .
➢ The loop statements are executed until the condition becomes false.
When the condition becomes false, the execution of loop stops.
In JavaScript, there are various types of loops.
•for loop
•for-in loop
•for-of loop
•while loop
•do-while loop
For loop
➢ If you want to execute statements for a specific number of times then you can use the
JavaScript for loop, which lets you iterate the statements for a fixed number of times.
➢ Syntax
for(initialization; condition; iteration)
{
// statements
}

➢ The idea here is to initialize a counter, set a condition until which


the loop will run, and keep on incrementing or decrementing the
counter so that after certain iteration the condition fails, and the
loop exits. If the condition never fails, the loop will keep on executing
infinitely.
Example

<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
For-in loop
➢ If you want to loop through the properties of a JavaScript Object then you can use the
JavaScript for…in loop.
➢ The for/in loop automatically iterates over the fields of an object and the loop stops when all the
fields are iterated
➢ Syntax

for(key in object)
{
// code statements
}

➢ When the loop will run, every time the key will get the value of the key using which we can
access the value against it in the object.
➢ In JavaScript, objects are in format {"key1":"value1","key2":"value2", ...} for which the for/in
loop can be used to iterate over all the fields of JavaScript object.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For/In Loop</h2>
<p>The for/in statement loops through the properties of an object.</p>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person)
{
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
 Output
The for/in statement loops through the properties of an object.
John Doe 25
For-of loop

 The JavaScript for/of loop lets you loop through the values of an iterable
object like an array, strings and more.
 Syntax

for(variable of iterable)
{
//code here
}
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For/Of Loop</h2>

<p>The for/of statement loops through the values of an iterable object.</p>

<script>
var cars = ['BMW', 'Volvo', 'Mini'];
var x;

for (x of cars) {
document.write(x + "<br >");
}
</script>

</body>
Output:
The for/of statement loops through the
values of an iterable object.
BMW
Volvo
Mini
While loop

 The JavaScript while loop iterates the elements for the infinite number of
times. It should be used if number of iteration is not known.
 Syntax
while (condition)
{
code to be executed
}
Example of while loop

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
 Output

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
do-while
➢ Just like the while loop, the do...while loop lets you iterate the code block as
long as the specified condition is true.
➢ In the do-while loop, the condition is checked after executing the loop. So,
even if the condition is true or false, the code block will be executed for at
least one time.
➢ Syntax
do {
// code block to be executed
}
while (condition);
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Do/While Loop</h2>
<p id="demo"></p>
<script>
var text = ""
var i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
Function

 A function is a set of statements that take inputs, do some specific computation,


and produces output.
 Basically, a function is a set of statements that performs some tasks or does some
computation and then return the result to the user.
 The idea is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for different
inputs, we can call that function.
 For example- If you are building an application for Student Management in which
you take data from a student during the registration process and then that data is
used at the time of identity card printing, mark sheet printing, any notice printing
or anywhere else, then one approach would be that wherever you want student
data you can use the student id, query the database and find all the
information about the student. You will have to write the same code wherever
you want student information. But this will lead to code repetition and if you have
to change something in this logic of fetching student data, you will have to make
the changes everywhere.
The better approach to this problem would be defining a
function, which takes student id as input, queries the database
and returns the student data as output, and then use this
function anywhere we want by just calling it. Now, if you have
to change something in the logic, you can do it easily.
 JavaScript function is a set of statements that are used to perform a specific
task.
 It can take one or more input and can return output as well. Both, taking
input and returning an output are optional.
 Using functions avoids repetition of the code as we need to write the code
only once and then the code can be called anywhere using function name.
 Syntax

function name(parameter1, parameter2, parameter3)


{
// code to be executed
}
 Function parameters are listed inside the parentheses () in the function
definition.
 Function arguments are the values received by the function when it is
invoked.
 Inside the function, the arguments (the parameters) behave as local
variables.
Function Calling

 The code inside the function will execute when "something" invokes (calls)
the function:
1. When an event occurs (when a user clicks a button)
2. When it is invoked (called) from JavaScript code
3. Automatically (self invoked)
Function Return
➢ When JavaScript reaches a return statement, the function will stop executing.
➢ If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
➢ Functions often compute a return value.
➢ The return value is "returned" back to the "caller":
➢ functions can be parameterized and non-parameterized
➢ A function that does not take any parameters/inputs is known as non-
parametrized function.
➢ A function that takes parameters/inputs which must be defined within
parenthesis is known as a parameterized function.
➢ When we call a function, we can provide custom values for these
parameters which are then used in function defintion.
➢ Use return statement.
➢ we can categorize functions into two category:

Function

User defined Built-in


function Functions
JavaScript User-defined Function

➢ JavaScript allows us to define our own functions as per our requirements.


➢ Creating a User-defined Function:
✓ Use function keyword followed by the function name and parentheses ( )
✓ A function can have zero or more parameters separated by commas.
✓ function body
✓ Return statement
✓ Syntax

function_name(parameter-1, parameter-
2,...parameter-n)
{
// function body
}
 After creating a function, we can call it anywhere in our script. The syntax for
calling a function is given below:

function_name(val-1, val-2, ..., val-n);

➢ Here, list of parameters represents the values passed to the funtion


during function call, which the function has specified in function
definition.
➢ If a function does not take any parameters then we don't have to
provide any value while calling the function.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript function parameters</h1>
<script>
function ShowMessage(firstName, lastName)
{
alert("Hello " + firstName + " " + lastName);
}
ShowMessage("Steve", "Jobs", "Mr.");
ShowMessage("Bill");
ShowMessage();
</script>
</body>
</html>
Buit-in Functions

➢ Functions that are provided by JavaScript itself as part of the scripting language, are known
as built-in functions.
➢ JavaScript provides a rich set of the library that has a lot of built-in functions.
➢ Some examples of the built-in functions are : alert(), prompt(), parseInt(), eval() etc.
 We can also create function with default parameters
 For example-

function printValue(a=1, b)
{
Document.write("a = " + a + " and b = " + b);
}

printValue(); // print: a = 1 and b = undefined


printValue(7); // print: a = 7 and b = undefined
printValue(7, 3); // print: a = 7 and b = 3
JavaScript Popup Boxes

 Alert Box
 An alert box is often used if you want to make sure information comes through to
the user.
 When an alert box pops up, the user will have to click "OK" to proceed.
<script>
alert("Hello World!")
</script>
JavaScript Popup Boxes - 2

Confirm Box
 A confirm box is often used if you want the user to verify or accept something.
 When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
 If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
JavaScript Popup Boxes - 3

 Prompt Box
 A prompt box is often used if you want the user to input a value before entering a
page.
 When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
 If the user clicks "OK“, the box returns the input value. If the user clicks "Cancel“,
the box returns null.
Prompt Box Example

<script>
x=prompt (“Adınızı Yazınız”, “ ”)
document.write(“Merhaba <br>”,+x)
</script>
Events

➢ Event is a action that is performed on web page


➢ When JavaScript is used in HTML pages, JavaScript can "react" on these
events.
 When javascript code is included in HTML, js react over these events and
allow the execution.
 This process of reacting over the events is called Event Handling.
 Thus, js handles the HTML events via Event Handlers.
 some examples of HTML events:
▪ An HTML web page has finished loading
▪ An HTML button was clicked
 Some of the HTML events and their event handlers are:
 Mouse Event
Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.


 Keyboard events:

Event Event Handler Description


Performed

Keydown & onkeydown & onkeyup When the user press and then release the key
Keyup
 Form Event

Event Event Handler Description


Performed

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a form element
 Window/Document events

Event Event Description


Perfor Handle
med r

load onload When the browser finishes the loading of the page

unload onunlo When the visitor leaves the current webpage, the browser unloads it
ad

resize onresiz When the visitor resizes the window of the browser
e
Example of click event

<html>
<body>
<script language="Javascript" type="text/Javascript">
function clickevent()
{
document.write("This is javascript program");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
Output:
Example of MouseOver Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("Mouseover event");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Output:
Example of Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
</html>
 Output:
Example of keydown event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
 Output:
Example of loadEvent()

<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">

<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
 Output:
Regular Expression
➢ A regular expression is a sequence of characters that forms a search
pattern.
➢ The search pattern can be used for text search and text replace
operations.
➢ A regular expression can be a single character, or a more complicated
pattern.
➢ Regular expressions can be used to perform all types of text search
and text replace operations.
 Regular expressions are frequently used to test whether or not a string
entered in an HTML form has a certain format.

 For example, you want to test if a user entered a string that contains 3
consecutive digits.
\d\d\d
 JavaScript provides regular expression capabilities through instances of the built-in
RegExp object.
 Syntax

var regTest = new RegExp(pattern,


modifiers);

✓ Pattern specifies the patthern of an expression


✓ Modifiers specify if a search should be global, case-senstive
 Following are the modifiers which we use:

Modifier Description

i Perform case-insensitive matching

g Perform a global match (find all matches


rather than stopping after the first match)

m Perform multiline matching


 match() is a method of a String instance returns true if its string matches the
pattern; otherwise, returns false.
For example:
var word = “I am a FSU student”;
var re = /fsu/i;
if(word.match(re)) alert(“Yes”);
else alert(“No”);
Regular Expression patterens

Brackets are used to find a range of characters:

Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
 Metacharacters are characters with a special meaning:

Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word
like this: \bWORD, or at the end of a
word like this: WORD\b
\uxxxx Find the Unicode character specified by
the hexadecimal number xxxx
 Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more
occurrences of n
n? Matches any string that contains zero or one
occurrences of n
➢ The test() method is a RegExp expression method.
➢ It searches a string for a pattern, and returns true or false, depending on the result.
➢ The following example searches a string for the character "e":

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Search for an "e" in the next paragraph:</p>
<p id="p01">The best things in life are free!</p>
<p id="demo"></p>
<script>
text = document.getElementById("p01").innerHTML;
document.getElementById("demo").innerHTML = /e/.test(text);
</script>
</body>
</html>
Array and Objects in JavaScript

➢ Array is group of elements that can be accessed through subscript.


➢ Array can be thought of list
➢ Unlike in some languages, values in JavaScript arrays do not all have be of
same data type
➢ An array is a special variable, which can hold more than one value at a time.
 Every value is associated with numeric index starting with 0.
 The following figure illustrates how an array stores values.
 Array elements stored at continues memory location
 There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
JavaScript array literal
 The syntax of creating array using array literal is given below
var arrayname=[value1,value2.....valueN];

Example-

<html>
<body> Output:
<script>
var emp=["Sonoo","Vimal","Ratan"]; Sonoo
for (i=0;i<emp.length;i++){ Vimal
document.write(emp[i] + "<br/>"); Ratan
}
</script>
</body>
</html>
JavaScript Array directly (new keyword)
➢ Syntax
➢ new keyword is used to create instance of array.

var arrayname=new Array();

<html>
<body>
<script> Output:
Arun
var i; Varun
var emp = new Array(); John
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] +
"<br>");
}
</script>
JavaScript array constructor (new keyword)
 you need to create instance of array by passing arguments in constructor so
that we don't have to provide value explicitly
 Example
Output:
<html>
<body> Jai
<script> Vijay
var emp=new Array("Jai","Vijay","Smith"); Smith
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
Types of array

Array

Associative
Index array
array

Index Array:
➢ This type of array indexed numerically
➢ By default index of first element is 0.
➢ All are above examples of indexed array
Array Properties

Properties Description

length Sets or returns the number of


elements in an array
array
The following table lists the standard methods of the Array object:

Method Description
concat() Merge two or more arrays, and
returns a new array.
copyWithin() Copies part of an array to another
location in the same array and
returns it.

entries() Returns a key/value pair Array


Iteration Object.
every() Checks if every element in an array
pass a test in a testing function.
fill() Fill the elements in an array with a
static value.
filter() Creates a new array with all elements
find() Returns the value of the first element in
an array that pass the test in a testing
function.
findIndex() Returns the index of the first element in
an array that pass the test in a testing
function.
forEach() Calls a function once for each array
element.
from() Creates an array from an object.
includes() Determines whether an array includes a
certain element.
indexOf() Search the array for an element and
returns its first index.
isArray() Determines whether the passed value is
an array.
join() Joins all elements of an array into a
string.
keys() Returns a Array Iteration Object,
containing the keys of the original
array.
lastIndexOf() Search the array for an element,
starting at the end, and returns its last
index.
map() Creates a new array with the results of
calling a function for each array
element.
pop() Removes the last element from an
array, and returns that element.
push() Adds one or more elements to the end
of an array, and returns the array's new
length.
reduce() Reduce the values of an array to a
single value (from left-to-right).
reduceRight() Reduce the values of an array to a
reverse() Reverses the order of the elements in an array.

shift() Removes the first element from an array, and


returns that element.
slice() Selects a part of an array, and returns the new
array.
some() Checks if any of the elements in an array passes
the test in a testing function.

sort() Sorts the elements of an array.


splice() Adds/Removes elements from an array.
toString() Converts an array to a string, and returns the
result.
unshift() Adds new elements to the beginning of an array,
and returns the array's new length.

values() Returns a Array Iteration Object, containing the


values of the original array.
toString() Example

<html>
<!DOCTYPE html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and get a list of car models</p>
<button onclick="arrayToString()">Try it</button>
<p id="text"></p>
</body>
Javascript funcion

function arrayToString()
{ var cars = ["Audi", "Mazda", "BMW", "Toyota"];
document.getElementById("text").innerHTML = cars.toString();
// output: Audi, Mazda, BMW, Toyota
}
Join method

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and see how the join method works</p>
<button onclick="carsArrayJoin()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function

function carsArrayJoin() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
document.getElementById("text").innerHTML = cars.join(" - ");
}
Output:
Pop()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and see how the pop method works</p>
<button onclick="carsPop()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function

function carsPop() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.pop();
document.getElementById("text").innerHTML = cars.toString();
}
Output:
Push()

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js">
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and see how the push method works</p>
<button onclick="carsPush()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function carsPush() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.push("new");
document.getElementById("text").innerHTML = cars.toString();
}

Output:
Shift()

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js">
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button to remove the first element of the array</p>
<button onclick="carsShift()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function carsShift() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.shift();
document.getElementById("text").innerHTML = cars.toString();
}

Output:

:
Unshift()

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js">
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and see how the unshift method works</p>
<button onclick="carsUnshift()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function carsUnshift() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.unshift("new");
document.getElementById("text").innerHTML = cars.toString();
}

Output:
Splice()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button and see how the splice method works</p>
<button onclick="spliceArray()">Try it</button>
<p id="text"></p>
</body>
</html>
JavaScript function
function spliceArray() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.splice(2, 0, "new", "newer");
document.getElementById("text").innerHTML = cars.toString();
}

Output:
Sort()

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button to output sorted array</p>
<button onclick="sort()">Try it</button>
<p id="text"></p>
</body>
</html>
JavaScript function()
function sort() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.sort();
document.getElementById("text").innerHTML = cars.toString();
}

Output:
Reversearray()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js">
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click the button to output sorted and reversed array</p>
<button onclick="reverseArray()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function reverseArray() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
cars.sort();
cars.reverse();
document.getElementById("text").innerHTML =
cars.toString();
}
Output:
Concat()
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js">
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>See how you can add two arrays</p>
<button onclick="concatArrays()">Try it</button>
<p id="text"></p>
</body>
</html>
Javascript function
function concatArrays() {
var cars = ["Audi", "Mazda", "BMW", "Toyota"];
var people = ["Joe", "Leona"];
var joined = cars.concat(people);

document.getElementById("text").innerHTML = joined.toString();
}

Output:
Slice()

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Click and look how the slice method works</p>
<button onclick="sliceArrays()">Try it</button>
<p id="text"></p>
</body>
</html>
JavaScript function

function sliceArrays() {
var cars = ["Audi", "Mazda", "BMW", "Toyota", "Suzuki"];
var myCars = cars.slice(1, 3);
document.getElementById("text").innerHTML =
myCars.toString();
}

Output:
Associative Array

 Associative arrays are used to store data in key-value pairs.


 Keys are used as index
 The advantage of this is that the keys can be meaningful which can be make
it easier to refer to an element in array.
 For e.g
Rainbow[“vio”]=“violet”;
Rainbow[“yell”]=“Yellow”;
Example of associative array:

Example:

var o = new Object();


o["one"] = 1; o["two"] = 2;
o["three"] = 3;
for(var i in o)
{
document.write(i + "=" + o[i] + '<br>');
}
one=1
two=2
Output:
three=3
JavaScript Built in Objects
 Javascript several built-in or core language objects.
 Built-in objects are not related to any Window or DOM object model.
 These objects are used for simple data processing in the JavaScript.

We alredy see the array object,Now we see the Math object.


Math Object
 The Math object is used to perform simple and complex arithmetic
operations.
 The Math object provides a number of properties and methods to work with
Number values
 The Math object does not have any constructors. All of its methods and
properties are static; that is, they are member functions of the Math object
itself. There is no way to create an instance of the Math object.
 Properties of math object
Math Property Description
SQRT2 Returns square root of 2.
PI Returns Π value.
E\ Returns Euler's Constant.
LN2 Returns natural logarithm of 2.
LN10 Returns natural logarithm of 10.
LOG2E Returns base 2 logarithm of E.
LOG10E Returns 10 logarithm of E.
Math Methods
Methods Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a
number.
ceil() Returns the smallest integer greater
than or equal to a number.
cos() Returns cosine of a number.
floor() Returns the largest integer less than or
equal to a number.
log() Returns the natural logarithm (base E) of
a number.
max() Returns the largest of zero or more
numbers.
min() Returns the smallest of zero or more
numbers.
pow() Returns base to the exponent power,
that is base exponent.
Number Object
➢ The Number objects represents numerical data, either integers or floating-point numbers.
➢ A Number objects are created using the Number() constructor

var num = new number(value);


Properties of Number object

Constructor Returns the function that created the


Number object.
MAX VALUE Returns maximum numerical value
possible in JavaScript.
MIN VALUE Returns minimum numerical value
possible in JavaScript.
NEGATIVE INFINITY Represent the value of negative
infinity.
POSITIVE INFINITY Represent the value of infinity.

Prototype - Add properties and methods to an


object.
Methods of Number object
Method Description
toExponential() Converts a number into exponential
notation.

toFixed() Formats a number with a specific


number of digits to the right of the
decimal.

toLocaleString() -- Returns a string value version of the


current number in a format that may
vary according to a browser's locale
settings.

toPrecision() - Defines how many total digits to display


of a number.

toString() - Returns the string representation of the


number's value.
Date Object

 JavaScript provides support for working with dates and time through the Date
object.
 Date object allows you to get and set the year, month, day, hour, minute,
second and millisecond fields.
 Date object can be created as :
var today = new Date( );
Methods of Date
Date() Returns current date and time.

getDate() Returns the day of the month.

getDay() Returns the day of the week.

getFullYear() Returns the year.

getHours() Returns the hour.

getMinutes() Returns the minutes.

getSeconds() Returns the seconds.

getMilliseconds() Returns the milliseconds.

getTime() Returns the number of milliseconds since


January 1, 1970 at 12:00 AM.
getTimezoneOffset() Returns the timezone offset in minutes
for the current locale.
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes() Sets the minutes.
setSeconds() Sets the seconds.
setMilliseconds() Sets the milliseconds.
setTime() Sets the number of milliseconds since
January 1, 1970 at 12:00 AM.
setMonth() Sets the month.
toDateString() Returns the date portion of the Date as
a human-readable string.
toLocaleString() Returns the Date object as a string.
toGMTString() Returns the Date object as a string in
GMT timezone.
valueOf() Returns the primitive value of a Date
object.
Example
<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</center>
</body>
</html>
Output:
String Object

 String objects are used to work with text.


 It works with a series of characters.
 Syntax

var variable_name = new String(string);

➢ Example

var s = new String(string);


 String Properties

Properties Description
length It returns the length of the string.
prototype It allows you to add properties and
methods to an object.
constructor It returns the reference to the
String function that created the
object.

String Methods

Methods Description
charAt() It returns the character at the
specified index.
charCodeAt() It returns the ASCII code of the
character at the specified position.
concat() It combines the text of two strings
and returns a new string.
Methods Description
indexOf() It returns the index within the calling String
object.
match() It is used to match a regular expression
against a string.
replace() It is used to replace the matched substring
with a new substring.
search() It executes the search for a match between a
regular expression.
slice() It extracts a session of a string and returns a
new string.
split() It splits a string object into an array of strings
by separating the string into the substrings.
toLowerCase() It returns the calling string value converted
lower case.
toUpperCase() Returns the calling string value converted to
uppercase.
Example of String object
<html>
<body>
<center>
<script type="text/javascript">
var str = "CareerRide Info";
var s = str.split();
document.write("<b>Char At:</b> " + str.charAt(1)+"<br>");
document.write("<b>CharCode At:</b> " + str.charCodeAt(2)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf("ide")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
</script>
<center>
</body>
</html>
Output:
Boolean object in JavaScript

 It is used to convert a non-Boolean value to a Boolean value (true or false).


 Methods of Boolean Object
Method Description
toSource() Returns a string containing the
source of the Boolean object; you
can use this string to create an
equivalent object.

- toString() - Returns a string of either "true" or


"false" depending upon the value of
the object.
valueOf() - Returns the primitive value of the
Boolean object
Java Script HTML DOM
 JavaScript can access all the elements in a webpage making use of Document
Object Model (DOM).
 In fact, the web browser creates a DOM of the webpage when the page is
loaded. The DOM model is created as a tree of objects like this:
 One important property of DOM structure models is structural isomorphism:
if any two DOM implementations are used to create a representation of the
same document, they will create the same structure model, with precisely
the same objects and relationships.
 DOM is used to represent structure as well as behaviour of document.
 Using DOM, JavaScript can perform multiple tasks.
 It can create new elements and attributes, change the existing elements and
attributes and even remove existing elements and attributes.
 JavaScript can also react to existing events and create new events in the
page.
DOM model
 Window Object: Window Object is at always at top of hierarchy.
 Document object: When HTML document is loaded into a window, it becomes
a document object.
 Form Object: It is represented by form tags.
 Link Objects: It is represented by link tags.
 Anchor Objects: It is represented by a href tags.
 Form Control Elements:: Form can have many control elements such as text
fields, buttons, radio buttons, and checkboxes, etc.
DOM properties

Cookie Return all name/value pairs of cookies


in document
documentMode Return mode used by browser to render
the document
Domain Return domain name of server that
loaded the document
lastModified Return the date and time the document
was last modified
readyState Return loding status of document
Referrer Return URL of Document that loaded
current document

Title Sets or return title of document


URL Teturn full URL of document
Methods of DOM

write(“string”) Write given string to document


getElementById() returns the element having the given
id value.
getElementsByName() returns all the elements having the
given name value.
getElementsByTagName() returns all the elements having the
given tag name
getElementsByClassName() returns all the elements having the
given class name.
Writeln() Same as write() but adds newline
charcher after each statment
Clear() Clears document in window
Close() Close output stream previously opend
with document.open()
Example
<html>
<head>
<script type=“text/javascript”>
Function chk()
{
var firstname=document.getElementById(“fname”);
Var wrog=document.getElementsByName(“org”);
If(firstname.value!=“” && wrog.value!=“”)
Alert(“Hello”+firstname.value+”!”);
Else
Alert(“Would you please enter missing text”);
}
</script>
</head>
<body>
<h2>Workshop Registration</h2>
Your Name:<input type=“Text” id=“fname”><br>
<input type=“text” name=“org”><br>
<input type=“button” onclick=“chk()” value=“Register”>
</body>
Element Object

 In the HTML DOM, the Element object represents an HTML element, like P,
DIV, A, TABLE, or any other HTML element.
 Properties

property Description
Id Sets or return id of element
Value Return value of element
innerHtml Sets or return content of element
Length Return no of entries in element array
tagName Return tagname of element as string
in uppercase
Examples
Example 1

Assume:City name<input type=“text” id=cname”>


Then: var cn=document.getElementById(“cname”);
document.write(cn.id);//return cname
Document.write(cn.tagName);//return INPUT
Document.write(cn.value);//retrun text entered in element

Example 2:

<html>
<head>
<script type=“text/javascript”>
Function wel()
{
Var cname=document.getElementById(‘cname’);
Var bt=document.getElementById(‘btxt’);
HTML
Bt.innerHtml=cname.value;
}
</script>
</head>
<body>
<p>Welcome to<b id=“btxt’>City</b></p>
City Name<input type=:text” id=“cname”><br>
<input type=“button” onclick=“wel()” value=“Enter”>
</body>
</html>
Anchor Object

 The anchor object i.e. <a href>...</a> represents HTML hyperlink


 Syntax

<a name”#anchorname”>click here</a>

➢ You can access anchor by using getElementbyId()


➢ Properties of anchor object

Property Description
href Sets or return value of href attribute
of link
name Sets or return value of name
attribute of link
Form Object

 Form object represents form which is used to collect user input through
elements like text fields, check box and radio button, select option, text
area, submit buttons and etc.. and pass this data from and to server.
 Form object properties

Property Description
Action It sets and returns the value of the
action attribute in a form.
enctype It sets and returns the value of the
enctype attribute in a form.
Length It returns the number of elements in a
form.
Method It sets and returns the value of the
method attribute in a form that is GET
or POST.
Methods

Method Description
reset() It resets a form.
submit() It submits a form.
Hidden Object

 Hidden object represents a hidden input field in an HTML form and it is


invisible to the user.
 This object can be placed anywhere on the web page.
 It is used to send hidden form of data to a server.
 Syntax: <input type= “hidden”>

Hidden Object Properties

Property Description
Name It sets and returns the value of the
name attribute of the hidden input
field.
Type It returns type of hidden input
element of form
Password Object
 Password object represents a single-line password field in an HTML form.
 The content of a password field will be masked – appears as spots or asterisks
in the browser using password object
 Syntax: <input type= “password”>

 Password Object properties

Property Description
defaultValue It sets or returns the default value of
a password field.
maxLength It sets or returns the maximum
number of characters allowed in a
password filed.
Name It sets or returns the value of the
name attribute of a password field.
readOnly It sets or returns whether a password
fields is read only or not.
Size It sets or returns the width of a
password field.
Value It sets or returns the value of the
attribute of the password field.

Methods

Method Description
Select() It selects the content of a password
field.
Checkbox Object
 Check box object represents a checkbox in an HTML form.
 It allows the user to select one or more options from the available choices.
 Syntax:
<input type= “checkbox”>

➢ Checkbox Object Properties

Properties Description
Name It sets or returns the name of the
checkbox.
Type It returns the value “check”.
Value It sets or returns the value of the
attribute of a checkbox.
checked It sets or returns the checked state of
a checkbox.
defaultChecked It returns the default value of the
checked attribute.
 Checkbox Object Methods

Method Description
click() It sets the checked property.
Select Object

 Select object represents a dropdown list in an HTML form.


 It allows the user to select one or more options from the available choices.
 Syntax

<select> … </select>

Select Object Collections

Collection Description
options It returns a collection of all the
options in a dropdown list.
Select Object Properties
Property Description
Length It returns the number of options in a
dropdown list.
selectedIndex It sets or returns the index of the
selected option in a dropdown list.
Type It returns a type of form element.
name It returns the name of the selection
list.

Methods

Method Description
add() It adds an option to a dropdown list.
remove() It removes an option from a dropdown
list.
Option Object
 Option object represents an HTML <option> element.
 It is used to add items to a select element.
 Syntax

<option value> . . . </option>

 Option Object Properties:


Property Description
Index It sets or returns the index position of
an option in a dropdown list.
Text It sets or returns the text of an option
element.
defaultSelected It determines whether the option is
selected by default.
Value It sets or returns the value to the
server if the option was selected.
Methods

Methods Description
blur() It removes the focus from
the option.
focus() It gives the focus to the
option.
Example
<html>
<head>
<script type="text/javascript">
function optionfruit(select)
{
var a = select.selectedIndex;
var fav = select.options[a].value;
if(a==0)
{
alert("Please select a fruit");
}
else
{
document.write("Your Favorite Fruit is <b>"+fav+".</b>");
}
}
</script>
</head> Output:
<body>
<form>
List of Fruits:
<select name="fruit">
<option value="0">Select a Fruit</option>
<option value="Mango">Mango</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option> Your favourite fruit is
<option mango
value="Strawberry">Strawberry</option>
<option value="Orange">Orange</option>
</select>
<input type="button" value="Select"
onClick="optionfruit(this.form.fruit);">
</form>
</body>
</html>
Radio Object
 Radio object represents a radio button in an HTML form.
 Syntax: <input type= “radio”>

Radio Object Properties:

Property Description
Checked It sets or returns the checked state of
a radio button.
defaultChecked Returns the default value of the
checked attribute.
Name It sets or returns the value of the
name attribute of a radio button.
Type It returns the type of element which is
radio button.
Value It sets or returns the value of the
radio button.
Radio Object Methods

Method Description
blur() It takes the focus away from the radio
button.
click() It acts as if the user clicked the button.
focus() It gives the focus to the radio button.
Text Object
➢ Text object represents a single-line text input field in an HTML form.
➢ Text Object Properties
Property Description
Value It sets or returns the value of the text
field.
defaultValue It sets or returns the default value of a
text field.
Name It sets or returns the value of the name
attribute of a text field.
maxLength It sets or returns the maximum number of
characters allowed in a text field.

readOnly It sets or returns whether a text field is


read-only or not.
Size It sets or returns the width of a text
field.
Textarea Object

 Textarea object represents a text-area in an HTML form.


 Syntax
<textarea> . . . </textarea>
➢ Properties of Textarea Object
Property Description
Value It sets or returns the value of the text field.
defaultValue It sets or returns the default value of a text field.
Name It sets or returns the value of the name attribute
of a text field.
Type It returns type of form element of a text field.
Rows It displays the number of rows in a text area.
Cols It displays the number of columns in a text area.
Callback function in JS
 In callback function,function passed to another function as an argument
,which is then called to invoke inside outer function to complete some kind of
action
 We can write our own callback function
 Example

Function doThing(other)
{
let x=7;
other();
}
function hello()
{
document.write(“hello”);
}
doThing(hello);
In –buit callback function

setTimeout()
➢ The setTimeout() method calls a function or evaluates an expression after a
specified number of milliseconds.
➢ Syntax
setTimeout(function, milliseconds, param1, param2, ...)

Parameter Description
function Required. The function that will be
executed
milliseconds Optional. The number of milliseconds
to wait before executing the code. If
omitted, the value 0 is used
param1, param2, ... Optional. Additional parameters to
Example
setTimeout(hello,2000,’Ranjit’);
Function doThing(other)
{
Let x=7;
Let name=‘steve’;
Other(name);
}
Function hello(nm,index,arr)
{
Document.write(“hello”,nm);
}
doThing(hello);
}
Foreach loop
➢ The forEach() method calls a function once for each element in an array, in order.
➢ Syntax

array.forEach(function(currentValue, index, arr), thisValue)

Parameter Description
function(currentValue, index, arr) Required. A function to be run for
each element in the array.
Function arguments:
Argument Description
currentValue Required. The
value of the
current element
index Optional. The
array index of the
current element
thisValue Optional. A value to be passed to the
function to be used as its "this" value.
If this parameter is empty, the value
"undefined" will be passed as its "this"
value
Example
Let names[‘Amir’,’Sarukh’,’Salman’,’Ajay’);
names.foreach(hello);
Function doThing()
{

Let x=7;
Let name=‘steve’;
Other(name);
}
Function hello(nm,idx,arr)
{
Document.write(“hello”,nm);
}
doThing(hello);
}
Promises
 Promises are used to handle asynchronous operations in JavaScript.
 They are easy to manage when dealing with multiple asynchronous
operations
 Multiple callback functions would create callback hell that leads to
unmanageable code.Events were not good at handling asynchronous
operations
 Promises are the ideal choice for handling asynchronous operations in
the simplest manner.
 They can handle multiple asynchronous operations easily and provide
better error handling than callbacks and events.
 Benefits of Promises

1. Improves Code Readability


2. Better handling of asynchronous operations
3. Better flow of control definition in asynchronous logic
4. Better Error Handling
 Promise constructor takes only one argument,a callback function.
 Callback function takes two arguments, resolve and reject
 Perform operations inside the callback function and if everything went well
then call resolve.
 If desired operations do not go well then call reject.
var promise = new Promise(function(resolve, reject) {
const x = “solve";
const y = “solve"
if(x === y) {
resolve();
} else {
reject();
}
});

promise.
then(function () {
console.log('Success, You are a pass);
}).
catch(function () {
console.log('Some error has occured');
});
 Promise ConsumersPromises can be consumed by registering functions
using .then and .catch methods.
1. then()
then() is invoked when a promise is either resolved or rejected.
Parameters:
then() method takes two functions as parameters.
I. First function is executed if promise is resolved and a result is received.
II. Second function is executed if promise is rejected and an error is received.
(It is optional and there is a better way to hanlde error using .catch() method
 Syntax
)
.then(function(result){ //handle success },
function(error){ //handle error }

Example:promise resolved

var promise = new Promise(function(resolve, reject)


{
resolve('Geeks For Geeks');
})

promise
.then(function(successMessage)
{
//success handler function is invoked
console.log(successMessage);
}, function(errorMessage) {
console.log(errorMessage);
})
 2. catch()

 catch() is invoked when a promise is either rejected or some error has


occured in execution.
 Parameters:
-catch() method takes one function as parameter.Function to handle errors or
promise rejections.(.catch() method internally calls .then(null, errorHandler),
i.e. .catch() is just a shorthand for .then(null, errorHandler) )
 Syntax:

.catch(function(error){ //handle
error })
Example

var promise = new Promise(function(resolve, reject)


{
reject('Promise Rejected')
})

promise
.then(function(successMessage) {
console.log(successMessage);
})
.catch(function(errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});

You might also like