CMPN Ip Module-2.
CMPN Ip Module-2.
CMPN Ip Module-2.
<button type=“button”
onClick=“document.getElementById("demo").style.color=‘red’ “>
</button>
getElementById is a method,
innerHTML is a property. It is used to get or change any html element.
3.3 Objects in JavaScript
• JavaScript is an object-based scripting language. Almost everything is an object in
JavaScript. A JavaScript object is an entity having state (properties) and behavior
(methods). An object can group data together with functions needed to
manipulate it. Look around you, you will find many examples of real-world objects.
Such as table, board, television, bicycle, shop, bus, car, monitor etc. All these
tangible things are known as objects. Take an example of car object. It has
properties like name, model, weight, color etc. and methods like start, stop, brake
etc. All cars have same properties but contain different values from car to car. All
cars have same methods but perform differently.
Properties and methods of object's are accessed with '.' operator.
JavaScript supports 2 types of objects built-in objects and user
defined objects.
1. Built in objects such as Math, String, Array, Date etc.
2. JavaScript gives facility to create user defined objects as per
user requirements. The ‘new’ keyword is used to create new
object in JavaScript.
e.g.
d= new Date();
// ‘d’ is new instance created for Date object.
Following are some of the predefined methods and properties for DOM object.
Property Description
Method Description
function makeNewWindow()
{
var newwin=window.open();
newwin.document.write("<h1>This is new window</h1>");
newwin.document.body.style. backgroundcolor="skyblue";
}
</script>
</head>
<body>
<form>
<input type="button" value="Create New Window” onClick="makeNewWindow()">
</form></body>
</html>
<!DOCTYPE html> <html>
<head>
<script type="text/javascript"> function sampleFunction()
{
window.setTimeout(next, 4000);
}
function next()
{
alert("4 seconds have passed");
}
</script></head>
<body style="background-color:cyan"> <h1
align="center">
Click button and wait for message </h1>
<input type="button" value="Timeout function"
onClick="sampleFunction()"> </body>
</html>
3.5 JavaScript Built-in Objects
JavaScript has several built-in or core language objects. These
built-in objects are available regardless of window content and
operates independently of whatever page browser has loaded.
These objects provide different properties and methods that are
useful while creating live web pages.
String Object :
• String is used to store zero or more characters of text within
single or double quotes. String object is used to store and
manipulate text.
Example :
var str="Information Technology";
document.write ("length of string is :-" + str.length);
document.write ("Substring is :-" + str.substr (12,10));
Math Object :
The built-in Math object includes mathematical constants and
functions. You do not need to create the Math object before using it.
Following table contains list of math object methods:
e.g. var x=56.899; alert(Math.ceil(x));
JavaScript Form Validation
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
JavaScript Retype Password Validation
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
} }
JavaScript Form Validation
HTML form validation can be done by JavaScript.
• If a form field (fname) is empty, this function alerts a message,
and returns false, to prevent the form from being submitted:
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
HTML Form Example
<form name="myForm" action="/
action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Regular Expression
• A regular expression is a pattern of characters.
• The pattern is used to do pattern-matching "search-and-replace" functions on text.
• In JavaScript, a RegExp Object is a pattern with Properties and Methods
example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Do a case-insensitive search for "w3schools" in a string:</p>
<p id="demo"></p>
<script>
let text = "Visit W3Schools";
let pattern = /w3schools/i;
let result = text.match(pattern);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Exception Handling in JavaScript
• An exception signifies the presence of an abnormal condition which
requires special operable techniques. In programming terms, an exception
is the anomalous code that breaks the normal flow of the code. Such
exceptions require specialized programming constructs for its execution.
What is Exception Handling
• In programming, exception handling is a process or method used for
handling the abnormal statements in the code and executing them. It also
enables to handle the flow control of the code/program. For handling the
code, various handlers are used that process the exception and execute
the code. For example, the Division of a non-zero value with zero will
result into infinity always, and it is an exception. Thus, with the help of
exception handling, it can be executed and handled.
• In exception handling:
• A throw statement is used to raise an exception. It means when an
abnormal condition occurs, an exception is thrown using throw.
• The thrown exception is handled by wrapping the code into the try…
catch block. If an error is present, the catch block will execute, else
only the try block statements will get executed.
• Thus, in a programming language, there can be different types of
errors which may disturb the proper execution of the program.
Types of Errors
• While coding, there can be three types of errors in the code:
• Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming language, a
syntax error may appear.
• Runtime Error: When an error occurs during the execution of the program, such an error is known
as Runtime error. The codes which create runtime errors are known as Exceptions. Thus, exception
handlers are used for handling runtime errors.
• Logical Error: An error which occurs when there is any logical mistake in the program that may not
produce the desired output, and may terminate abnormally. Such an error is known as Logical error.
Error Object
• When a runtime error occurs, it creates and throws an Error object. Such an object can be
used as a base for the user-defined exceptions too. An error object has two properties:
1. name: This is an object property that sets or returns an error name.
2. message: This property returns an error message in the string form.
• EvalError: It creates an instance for the error that occurred in the eval(), which is a global
function used for evaluating the js string code.
• InternalError: It creates an instance when the js engine throws an internal error.
• RangeError: It creates an instance for the error that occurs when a numeric variable or
parameter is out of its valid range.
• ReferenceError: It creates an instance for the error that occurs when an invalid reference is
de-referenced.
• SyntaxError: An instance is created for the syntax error that may occur while parsing the
eval().
• TypeError: When a variable is not a valid type, an instance is created for such an error.
• URIError: An instance is created for the error that occurs when invalid parameters are passed
in encodeURI() or decodeURI().
Exception Handling Statements
There are following statements that handle if any exception occurs:
• throw statements
• try…catch statements
• try…catch…finally statements.
A try…catch is a commonly used statement in various programming
languages. Basically, it is used to handle the error-prone part of the code. It
initially tests the code for all possible errors it may contain, then it
implements actions to tackle those errors (if occur). A good programming
approach is to keep the complex code within the try…catch statements.
• try{} statement: Here, the code which needs possible error testing is kept
within the try block. In case any error occur, it passes to the catch{} block
for taking suitable actions and handle the error. Otherwise, it executes
the code written within.
syntax
catch{} statement: This block handles the error of the code by
executing the set of statements written within the block. This block
contains either the user-defined exception handler or the built-in
handler. This block executes only when any error-prone code needs to
be handled in the try block. Otherwise, the catch block is skipped.
try{
expression; } //code to be written.
catch(error){
expression; } // code for handling the error.
<html>
<head> Exception Handling</br></head>
<body>
<script>
try{
var a= ["34","32","5","31","24","44","67"]; //a is an array
document.write(a); // displays elements of a
document.write(b); //b is undefined but still trying to fetch its value. Thus catch block
will be invoked
}catch(e){
alert("There is error which shows "+e.message); //Handling error
}
</script>
</body>
</html>
JavaScript Events
• The change in the state of an object is known as an Event.
• In html, there are various events which represents that some activity
is performed by the user or by the browser.
• 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.
Mouse events:
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
<div id="id01"></div>
<script>
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
<script src="myTutorials.js"></script>
Example Explained
1: Create an array of objects.
Use an array literal to declare an array of objects.
Give each object two properties: display and url.
Name the array myArray:
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]
2: Create a JavaScript function to display the array.
Create a function myFunction() that loops the array objects, and display the content as HTML links:
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
3: Use an array literal as the argument (instead of the array variable):
Call myFunction() with an array literal as argument:
myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]);
4: Put the function in an external js file
Put the function in a file named myTutorials.js:
myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]);
JSON Http Request
• A common use of JSON is to read data from a web server, and display
the data in a web page.
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url ="file:///Users/amitaylani/Downloads/sample3.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>