If there is any mismatch while confirming the password, you will be seeing this error message.
JavaScript is a scripting language, which are mainly used to write scripts.
In order to have a JavaScript in a HTML page, we need to inform the browser that the page contains JavaScript content by placing them inside script tag element.
JavaScript code can even be defined in an external file and that file path is referred in the src attribute of script element.
script src="../JavaScript/sample.js"
//No script goes here
/script
|
Defining a script in an external file helps in its reusability.
src attribute specifies the external file path as an URL which can be :
an absolute URL like http://www.javascript.com/sampleJavascript.js (refers to another web site)
a relative URL like /sample/sampleJavascript.js (refers to a file within a web site)
Note: To write something in a html page using JavaScript, we use document.write() .
Basic Syntax of JavaScript
Before writing JavaScript code like password matching, let us first understand few important things about the syntax of the JavaScript language:
It is a case sensitive language
Semicolon(;) is used to separate statements
It considers spaces, tabs and new line characters as whitespace characters
It supports both single as well as multi line comments
//single line comment
/* multi line
comment */
Identifiers (to identify a variable or function) can only start with alphabetic characters or "$" or "_" . Subsequent characters for the identifier can be alphabet or numeric.
Example: number_of_trainees, catch22, _DB_ID
Datatypes in JavaScript
When we want to store some data in JavaScript, we should tell what exactly the data is and how we intend to use it.
Try to identify the datatypes that can be used in the gmail signup page
JavaScript categorizes and stores the data based on the type of data. JavaScript supports mainly these data types:
Number : To represent numeric values ( Example : 1, 2.5 etc. )
String : To represent text or sequence of characters ( Example : "Jack" ,'John' etc. )
Boolean : To represent Boolean values( Example : true, false )
Null : To initialize a variable, which has no object to refer
Undefined : To initialize a variable which has no value for it
Variables in JavaScript
We learnt to choose appropriate datatype for different input fields. To stores those values in browser memory for further processing we need variables.
JavaScript is a dynamic typed language like Python. So we need not specify the data type while declaring a variable. The data type of the variable will be automatically determined when the script is executed.
This means we can have the same variable associated with values of different data types during the program execution.
For example , let us have a variable v1.
In JavaScript variables should be declared by using the keyword var.
var v1 = 23; // v1 is now a variable of type Number
var v1 = "HelloWorld"; // v1 is now a variable of type String
var v1 = false; // v1 is now a variable of type Boolean
|
Scope of variables is by default global. If a variable is prefixed by the keyword "var" within a function then it is a local variable.
var id=1001; //Variable declaration. Type is decided by the usage
var name="Rajath";
document.write("h2");
document.write("Value of id is "+id+"br");
document.write("Value of name is "+name+"br");
//document.write() is used to display a message on the webpage
document.write("/h2");
Performing Operations in JavaScript
Comparison and Unary Operators
In Comparison Operators we have === and !==. They are slightly different than == and !=.
=== returns true if both the operands’ value and type are equal, but == only checks if both the operands’ value are equal.
var x='1'; //String type
var y=1; // Number type
|
So, x==y will return true and x===y will return false
Same way != will check only if the value is unequal while, !== will check if both value and type are unequal.
In Unary Operators we have typeof. This returns the data type of the operand.
Using the same example as above:
typeof x; //will return string
typeof(y); //will return number
|
new and instanceof Operators
There are also certain special operators like new.
This is used to create an instance of an object (can be user-defined or built-in).
var d = new Date(); //Here Date is a built-in object
|
In Relational Operators we have instanceof. This returns true if the object is of the specified object type.
var d = new Date();
d instanceof Date; //will return true
|
| var DA=2000;var basic = 10000; |
| var BoA=10000;
|
| var PF=850;
|
| var Gratuity=309;
|
| var str="In hand you recieve a salary of Rs.";
|
| var strTax="Tax you have to pay is Rs. ";
|
| var today= new Date();
|
| |
| FixedSalary=Basic+DA+BoA+PF+Gratuity; //usage of operators
|
| TakeHome=FixedSalary-(PF+Gratuity);
|
| Tax=(FixedSalary>20000)?((7.5/100)*FixedSalary):((5/100)*FixedSalary);
|
| |
| document.write("
");
|
| document.write(str+TakeHome+"br");
|
| document.write(strTax+Tax+ br);
|
| |
| document.write("typeof var str is: "+typeof(str)+"br"+"br");
|
| document.write( "var today is instanceof Date: \t"+"  ");
|
| document.write( today instanceof Date );
|
| document.write("/h2"); |
Conditionals and Loops
Now that we know the various data types and the operators, we need to know how to perform decision making and repetitive tasks.
Just like in Java, JavaScript also has control structures which allow us to control the flow of execution in our program. They are:
if
if-else
switch
for
while
do-while
break
continue
return
Conditional Statements
Syntax for conditional statements are as follows:
if (expression) {
//statements
}
if (expression) {
//statements
} else if{
//statements
} else{
//statements
}
switch (expression) {
case label_1: //statements
[break;]
. . .
case label_n: //statements
[break;]
default: //statements
[break;]
}
|
| document.write("h2");var num=3; |
| document.write("Cool Drinks vending machine br")
|
| if(num>0 && num<5 td="">5> |
| document.write("Item is available for the pressed number "+num+"br");
|
| |
| |
| switch(num){ //working of control structures
|
| |
| |
| case 1:document.write("Item is Fanta");
|
| break;
|
| |
| case 2:document.write("Item is Pepsi");
|
| break;
|
| |
| case 3:document.write("Item is Coke");
|
| break;
|
| |
| case 4:document.write("Item is Sprite");
|
| break;
|
| |
| }
|
| }
|
| |
| else{
|
| document.write("No item is available for the pressed number");
|
| }
|
| |
| document.write("/h2"); |
}
Looping Statements
Syntax for looping statements in JavaScript :
for (initial_expression; condition; increment/decrement_expression) {
//statements
}
for (variable in object) {
//statements
}
while (condition) {
//statements
}
do {
//statements
} while (condition) ;
Dialog Boxes
JavaScript provides several dialog boxes to interact with the user.
confirm("Would you like to exit?");
prompt("What is your lucky number?",0);
| var name=prompt("Please enter your name","");
|
| function display(enteredName){
|
| |
| if(enteredName!="" && enteredName!=null){
|
| |
| if(confirm("If entered name is "+enteredName+" , press OK to continue")==true){
|
| |
| alert(enteredName+" registered successfully");
|
| document.write("h2 Welcome "+enteredName+"/h2")
|
| }
|
| |
| }
|
| |
| else{
|
| alert("Name is mandatory");
|
| }
|
| |
| }
|
| |
| display(name); |
User Defined Functions
We are already familiar with working of functions, now let us understand some interesting features of user defined functions in JavaScript :
In JavaScript, every function is an object(of type Function) and functions are treated as first-class citizens, as they can :
be stored in a variable, array, or object
have properties
be passed to, and returned from, another function
A function can:
Also there is no restriction on the number of arguments passed to a function.
If we have passed extra parameters while invoking the function, those extra parameters can still be retrieved.
Creating Functions Using Function Statement
Function can be created either by using:
Function statement
Function expression
Let us understand how to create a function using function statement.
A function can be created using function keyword, followed by name of the function (functionName) and parameters(param1, param2,…). After that it also contains the statements which forms the body of the function inside curly braces({}).
Syntax:
function functionName(param1, param2,…){
//statements
}
|
Example:
function myFunction(num1,num2){
num3=num1*num2;
}
|
In the above example we have function named myFunction, which has parameters num1 and num2. The body of the function is placed inside the curly braces.
Now let us understand how to invoke the function defined in the previous example.
It can be invoked by using the name of the function (myFunction) and by passing necessary parameters.
eg |
| function myFunction(num1,num2){
|
| alert("You are now inside a function")
|
| num3=num1*num2;
|
| document.write(num3)
|
| }
|
| myFunction(10, 20); |
|
Function Expressions
Using function expression, we can create a function in two ways.
1. Without providing the function name i.e. anonymous functions
2. Providing the function name i.e. named functions
Let us first understand how to create an anonymous function.
A function can be created using the below syntax, which contains function keyword followed by the parameters(param1, param2,…).
function(param1,param2,…) {
//statements
}
|
Anonymous Function
In the below example we have a variable named myFun, followed by the function definition.
var myFun = function(num1, num2){
num3=num1*num2;
}
|
In order to invoke an anonymous function, we need a named identifier. In the above example named identifier for the function is myFun.
Named Function
A named function can be created using the below syntax, which contains function keyword followed by the functionName and parameters(param1, param2,…).
var myFun = function functionName(param1, param2 ,…) {
//statements
}
|
Let us understand with the help of an example.
var myFun = function myFunction(num1, num2 ) {
num3=num1*num2;
}
|
In order to invoke a named function, we need a named identifier. In the above example named identifier for the function is myFun.
How to Invoke Named Function?
Can we invoke the named function using its function name(myFunction) ?
A named function can be invoked by using its name myFunction, only when the function is invoked internally.
Otherwise if we are trying to invoke a named function outside its body, we should always use the named identifier (myFun) to invoke the named function.
When we have two ways to create a function, which is the most preferred one?
Functions expressions are very much easier to work with whenever we want to pass a function as a parameter to another function.
So if we want to pass a function as parameter, it is always preferred to create a function using function expression rather then function statement.
var myFun=function myFunction(num1,num2){
num3=num1*num2;
alert("calling myFunction internally");
myFunction(num2,num3);
}
myFun(1,2)
|
Built-in Functions :
There are some functions which are already provided by JavaScript. These are known as built-in functions.
These functions that are predefined globally and so can be used with any JavaScript object.
built-in function.
- eval()
- parseInt()
- parseFloat()
- Number()
- String()
- isFinite()
- isNaN()
eval() built-in function.
eval() is used to evaluate the JavaScript code that has been represented as a string.
Syntax:
Example:
var x=2, y=2;
eval("x * y") // 4
eval("2 * 2") // 4
eval("z = new Date()") // z=today’s date
parseInt()
parseInt() parses a string and returns an integer value of the radix specified (if not specified, default radix is 10 i.e. decimal number system).
Radix is the base in mathematical numeral systems like for Decimal (10), Hexadecimal (16), Octal (8) etc. Radix values can range from 2-36.
If parseInt() comes across a character in the string that is not a numeral, it will simply ignore it and all the other characters that are after it. Then it returns the integer value that it has parsed till that particular point.
Syntax:
parseInt(String, [radix])
|
Example:
parseInt("5"); // 5
parseInt("5.5"); // 5
parseInt("5p0"); // 5
parseInt("p50"); // NaN (Not a Number)
|
parseFloat()
parseFloat() parses a string and returns a floating point number.
If parseFloat comes across a character in the string that is not a numeral or '.' or '+' or '-' , it will simply ignore it and all the other characters that are after it. Then it returns the value that it has parsed till that particular point.
Syntax:
Example:
parseFloat("1.23"); // 1.23
parseFloat(".123"); // 0.123
parseFloat("1.23abc"); // 1.23
parseFloat("a123") // NaN
Number()
|
|
Number(), which is the constructor of Number object, converts value of an object to a number. If it is unable to convert the value, it returns NaN.
Syntax:
Example:
var x="123";
Number(x); // 123
Number("123"); // 123
Number("123.1"); // 123.1
Number(true); // 1
Number(false); // 0
Number("123abc"); // NaN
Number(new Date()); // number of milliseconds since January 1, 1970
|
String()
String() converts the value of an object to a string. It is the constructor of the String object.
Syntax:
String(1) // "1"
String(Boolean (0)) // "false"
|
isFinite()
isFinite() determines whether given argument is a finite number or not.
If the argument is NaN, Infinity, -Infinity then it returns false.
Syntax:
Example:
isFinite(0) // true
isFinite(NaN) // false
isFinite("Hi") // false
isFinite("12Hi") // false
|
isNaN()
isNaN() determines whether given argument is "NaN" or not.
If the argument to the function is not of type Number, then the argument is first coerced to a Number and then it is evaluated.
Syntax:
Example:
isNaN('12a'); // true
isNaN(12); // false
|
var a=isFinite(5-4); //true
var b=isNaN("4.4a"); //true
var c=isFinite(NaN); //false
Objects in JavaScript
In JavaScript an object is nothing but a collection of properties.
In simple terms a property is an association between a name and a value.
However the value can even be a function.
JavaScript provides many standard built-in objects. In addition to that it also provides an option to create user defined objects.
User defined objects in JavaScript can be created by using one of the following mechanisms.
Using literal notation
Using custom object constructor
Using constructor of Object
Creating Object Using Literal Notation
Syntax:
var obj = { property1 : value1,
5 : value2,
"prop" : value3 };
|
obj refers to the name of the object to be created
Each property name can be an identifier, a number or even a string literal
Property value can be a constant or even an expression whose value will be assigned to the property
All the properties are wrapped inside the curly braces for better readability and understanding
Example:
var emp_one = {
name : "John",
empNumber : 1001,
emailId : "Johny@123mail.com"
};
|
var trainee={traineeId:"329714",batch:"Jul15-LC1",stream:"JEE"}
document.write("h3 style='color:blue' Trainee object created using object literal notation/h3")
document.write("h3Trainee Details/h3")
document.write(trainee.traineeId+"br")
document.write(trainee.batch+"br")
document.write(trainee.stream)
|
Creating Object Using Constructor Function
An object can be created by using constructor function.
Syntax:
function Name(param1,param2,param3) {
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
};
var obj = new Name(p1,p2,p3);
|
Steps to create an object :
Create a constructor function which provides details about the Name, properties and methods of the object type.
Instantiate the object using new operator
Example:
function Employee(name,empNumber,emailId) {
this.name=name;
this.empNumber=empNumber;
this.emailId=emailId;
}
var emp_one = new Employee("John",1001,"John@infy.com");
|
Here we have created a constructor function Employee() to define the details about the object type.
We also created an object of type Employee using the new operator.
Note:
this is used to assign the values to the properties of an object.
It is better programming practice to always start the name of constructor function(Employee) with a capital letter.
function Employee(name,empNumber,emailId) {
this.name=name;
this.empNumber=empNumber;
this.emailId=emailId;
}
var emp_one = new Employee("John",1001,"John@infy.com");
Creating Object Using Object Constructor
|
Syntax:
var obj = new Object([value]);
obj.prop1 = "value1";
obj.prop2 = value2;
obj.prop3 = "value3";
|
This object constructor creates an object wrapper for the [value] passed
If the [value] passed is empty, null or undefined this object constructor creates an empty object and returns the same
If [value] is passed, then it creates and returns an object of value type
It also allows the addition of properties for the objects created
Example:
var emp_one = new Object();
emp_one.name = "John";
emp_one.empNumber = 1001;
emp_one.emailId = "John@infy.com";
|
In the above example, initially we created an empty object using the Object().
After creating the object we added properties for the empty object (name, empNumber, emailId).
For the emp_one object created above methods can be added and invoked as shown below.
emp_one.empDetails = function(){
// code goes here
};
emp_one.empDetails();
|
Let us have a look on one more example.
var obj = new Object(true);
|
In the above example Object() constructor will create and return an object of type Boolean.
Accessing the Object Properties
create an object using literal notation.
var emp_one = {
name : "John",
empNumber : 1001,
emailId : "John@infy.com" };
|
Let us understand the different ways to access the object properties.
To get the value: var name = emp_one.name;
To set the value: emp_one.name = "Hello";
To get the value: var name= emp_one["name"];
To set the value: emp_one["name"] = "John";
How can we access only property names present in object in emp_one?
var emp_one = {
name : "John",
empNumber : 1001,
emailId : "John@infy.com" };
|
In order to access only property names from the above object, Object.keys() function can be used.
keys() returns an array of property names of the object.
var props = Object.keys(emp_one);
|
Here props will contain an array of property names i.e name, empNumber, emailId.
Note: object[property] access should be used mainly when the property names are having space, hyphen, or one that starts with a number.
Built-in Objects in JavaScript
JavaScript has several standard built-in objects which have a global scope.
Numbers and dates
Text processing
Indexed collections
Structured data
Number Object
Number is a built-in object that allows us to work with numerical values.
A Number object is created using the Number() constructor.
Syntax:
Some of the commonly used attributes and methods for you to explore are as follows:
Number.NaN
Number.MAX_VALUE
Number.MIN_VALUE
Number.isFinite()
Number.isNaN()
Number.isInteger()
Math Object
Math is a built-in object that has properties and methods for mathematical constants and functions.
Math is not a constructor i.e. Math() does not exist. All its properties and methods are static.
Some of the commonly used attributes and methods for you to explore are as follows:
Math.PI
Math.SQRT2
Math.LN10
Math.abs()
Math.ceil()
Math.floor()
Note: Math functions have a precision that's implementation-dependent which means that different browsers can give a different result.
var x=new Number("89");
alert(x +" " +typeof(x));
var y=new Number("32wetf");
alert(y +" " +typeof(y));
alert("isFinite() of x"+" "+ isFinite(x))
alert("isNaN() of y"+" "+ isNaN(y))
alert("minimum value in JavaScript"+ " " +Number.MIN_VALUE)
alert("maximum value in JavaScript"+ " " +Number.MAX_VALUE)
alert( Math.floor(5.2) )
alert( Math.ceil(4.1) )
alert( Math.round(3.2) )
alert( Math.random() )
alert(Math.tan(0.78))
alert(Math.sin(0.78))
alert(Math.cos(0.78))
alert(Math.pow(2,3))
Date Object
Date is a built-in object which is used to create a Date instance.
All Date objects are calculated using the number of milliseconds since 1 January, 1970 UTC.
Date instance can be created using Date() constructor.
Some methods of object are: js10
Note: Month in Date is 0 based. js9
today=new Date();
alert("Today is (To locale string) :"+today.toLocaleString());
alert("toLocaleDateString()->"+today.toLocaleDateString())
alert("getdate()->"+today.getDate())
alert("getday()->"+today.getDay()) // day monday -1 friday -5
alert("gethours()->"+today.getHours())
alert("getminutes()->"+today.getMinutes())
alert("getmonth()->"+today.getMonth())
alert("getfullyear()->"+today.getFullYear())
alert("getseconds()->"+today.getSeconds())
alert("gettime()->"+today.getTime())
year=today.getYear();
nextyear=new Date((today.getFullYear()+1),0,1); // month starts from 0 - 11
days=(nextyear-today)/(24*60*60*1000);
String Object
String is a built-in object that allow us to work with string. A String object is created using the String() constructor.
Syntax :js11
js12
js13
Regular Expression
Regular Expressions are used for pattern matching.
The RegExp built-in object is used to create a regular expression object for pattern matching.
There are 2 ways to define a pattern:-
Example :
/E[1-9][0-9]{5}/ matches an employee ID starting with E with first digit between 1-9 and remaining five digits between 0-9
Example :
new RegExp("E[1-9][0-9]{5}")
|
var s=new String("Hello");
alert(s)
s1=s.concat("World");
alert(s1);
alert(s1.toLocaleString().substr(5,5));
alert(s1.toUpperCase().substring(5, 11));
alert(s1.charAt(4));
var s2=new String("Hello-World");
s3=s2.split("-") //here '-' is delimiter
alert(s3);
alert(/Java/.test("JavaStream")); // Returns true
var re = new RegExp("Java");
alert(re.test("JavaStream")); // Returns true
Array Object
Array built-in object is used to create arrays.
Different ways to create an Array are:
var arr1 = [element0,element1,...,elementN];
var arr2 = new Array(element0,element1,...,elementN);
var arr3 = new Array(arrayLength);
|
Some of the attributes/methods of an Array object are given below:js14
eg
var courseArray = ['HTML','CSS','JS','JSF'];
courseArray.forEach(function PrintThis (value, index, arr)
{
alert("value :" + value);
alert("index :" + index);
}
);
courseArray.pop()
courseArray.push("Angular")
alert(courseArray)
JSON - JavaScript Object Notation
|
JSON is a data exchange format derived from JavaScript which is text based. link
It is mainly used in web based applications for data exchange like in web services.
Object Literal Notation
|
|
JavaScript Object Notation
|
var emp_one = {
name : "John",
empNumber : 1001,
emailId : "John@infy.com"
}
| | var emp_one = {
"name": "John",
"empNumber": 1001,
"emailId":"John@infy.com"
}
|
JavaScript provides a standard built-in object called JSON which has methods for parsing and generating JSON data.
parse():
var json = '{ "firstName":"Infosys", "lastName":"Limited", "pincode":570017 }';
var company = JSON.parse(json); //will convert JSON string into an object
alert(company.firstName +" "+ company.lastName +" "+ company.pincode );
|
stringify():
var jScores = { "Java": 70, "JavaScript": 80, "CSS": 30 };
var tScores = JSON.stringify(jScores); //will convert object to JSON
alert(typeof(jScores)); // returns Object
alert(typeof(tScores)); // returns String
var trainees = { "Trainee" : [
{ "Name" : "Ram", "age" : 34 },
{ "Name" : "Raj", "age" : 23 }],
}
alert(trainees.Trainee[0].Name)
alert(trainees.Trainee[1].age)
var json = '{ "firstName":"Infosys", "lastName":"Limited", "pincode":570017 }';
var company = JSON.parse(json); //will convert JSON string into an object
alert(company.firstName +" "+ company.lastName +" "+ company.pincode );
var jScores = { "Java": 70, "JavaScript": 80, "CSS": 30 };
var tScores = JSON.stringify(jScores); //will convert object to JSON
alert(typeof(jScores)); // returns Object
alert(typeof(tScores)); // returns String
DOM - Document Object Model
|
Consider the gmail sign up password matching logic. In order to develop this logic, we need to know how to access the values of password and confirm password fields in JavaScript.js15
The values of these fields can be accessed with the help of DOM.
DOM (document object model) acts as a programming interface between HTML and JavaScript.
It turns HTML tags to objects, which can be accessed and manipulated by JavaScript
Our browser parses the HTML document and turns it into the DOM representation
js16
Here the DOM objects are shown along with the HTML code.
Before we can learn to access these DOM objects(also known as Nodes), we will see how they are arranged in a hierarchical fashion.
Note : Window object depicts our browser. It is root node for the rest of the objects.
DOM Hierarchy
js17
This is a simple hierarchy of the few important objects.
Let us see how we can access these objects in our JavaScript code by following this hierarchy.
Consider the code below :
form name="userlogin"
Usernameinput type="text" name="username"
Passwordinput type="text" name="pass"
/form
|
Here, the value in the Username textbox can be accessed in the JavaScript code as
js18
We know that every HTML document is represented by a Document object in a web browser.
DOM Properties and Methods
js19
To use any method or property, we have to use it in document.write() or document.URL format
Every form element present in a document is represented by a form object in DOM.
Note : console.log is used to print output in browser's console. Console can be viewed by pressing F12 in Chrome.
var sAnswer = window.prompt("Please enter your favorite color : choose from the following Yellow, Green, Red, Blue, Pink, Orange, Black, Grey");
document.bgColor = sAnswer;
document. write ("H1Welcome to " + sAnswer + " background :-)!!/H1HRWe are very happy to demonstrate the usage of document. write. Do remember to view the source!");
HTML Form as DOM Object
|
|
Let us now see the form object and various elements present in it.
Consider the code below:
Let’s see the various ways by which we can access the form elements.
Let us take the example of the first radio button value. It can be accessed as either of the two ways
document.form1.rad1[0].value
|
document.forms[0].elements[0].value
|
- action attribute is used to specify the action page URL
- Each form element in a document generates a form object
- Can be accessed using forms[] collection attribute of its parent document
form name="register"
Enter username .input value="John" id="name" name="username".
/form
to fetch the value entered in username text field
- document.getElementById(“name”).value
- document.register.username.value
Event Handling
Consider the gmail sign up password matching logic.
After entering the value for 'confirm you password', to invoke the function containing the logic we can make use of events and event handlers
Every action of a user or browser causes events on a web page.
HTML elements for which we want to handle the event, can specify event attributes.
Let us see, some of the common events and its corresponding event attributes.
We expect our page to respond accordingly to these events(isn’t that’s why we started with JavaScript, to make our page interactive).
The JavaScript code(called specifically as function) is written to respond to these events are called as event handlers.
The general syntax to define an event handler is:
event-attribute