Java Script Notes Sem-II-1
Java Script Notes Sem-II-1
Java Script Notes Sem-II-1
When you are telling the computer what to do, you also get to choose how it's
going to do it. That's where computer algorithms come in. The algorithm is
the basic technique used to get the job done. Let's follow an example to help
get an understanding of the algorithm concept.
Let's say that you have a friend arriving at the airport, and your friend needs to
get from the airport to your house. Here are four different algorithms that you
might give your friend for getting to your home:
The taxi algorithm:
1. Go to the taxi stand.
2. Get in a taxi.
3. Give the driver my address.
The call-me algorithm:
1. When your plane arrives, call my cell phone.
2. Meet me outside baggage claim.
The rent-a-car algorithm:
1. Take the shuttle to the rental car place.
2. Rent a car.
3. Follow the directions to get to my house.
The bus algorithm:
1.
2.
3.
4.
All four of these algorithms accomplish exactly the same goal, but each
algorithm does it in completely different way. Each algorithm also has a different
cost and a different travel time. Taking a taxi, for example, is probably the
fastest way, but also the most expensive. Taking the bus is definitely less
expensive, but a whole lot slower. You choose the algorithm based on the
circumstances.
Summary :- The sequence of steps to be performed in order to solve a
problem by the computer is known as an algorithm
For Example :-
The server then fetches the page named index.html and sends it to your
browser. Any computer can be turned into a Web server by installing server
software and connecting the machine to the Internet. There are many Web
server software applications, including public domain software from NCSA and
Apache, and commercial packages from Microsoft, Netscape and others.
Java script
Java script is a client slide scripting language which is used to change HTML
static page into dynamic pages or it brings interactivity in HTML web pages.
A client side scripting language means , it has support in the browser &
doesnt require a web server to be executed
Java script is supported by all major browsers and it is written inside HTML
document.
JavaScript
JavaScript is an object-based scripting language that is lightweight and crossplatform.
JavaScript is not compiled but translated. The JavaScript Translator (embedded
in browser) is responsible to translate the JavaScript code.
JavaScript Example
1. JavaScript Example
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Output:
Welcome to Javascript
JavaScript Comment
1. JavaScript comments
2. Advantage of javaScript comments
3. Single-line and Multi-line comments
</script>
1. JavaScript variable
2. JavaScript Local variable
3. JavaScript Global variable
A JavaScript variable is simply a name of storage location. There are two
types of variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as
identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or
dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different
variables.
Correct JavaScript variables
var x = 10;
var _value="sonoo";
Incorrect JavaScript variables
var 123=30;
var *aa=320;
Lets see a simple example of JavaScript variable.
Program 5:
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Output of the above example: 30
</body>
</html>
O/P: 100
Description
String
Number
Boolean
Undefined
Null
Description
Object
Array
RegExp
Description
Addition
Example
10+20 = 30
Subtraction
20-10 = 10
Multiplication
10*20 = 200
Division
20/10 = 2
Modulus (Remainder)
20%10 = 0
++
Increment
--
Decrement
Description
Example
==
Is equal to
10==20 = false
===
10==20 = false
!=
Not equal to
10!=20 = true
!==
Not Identical
20!==20 = false
>
Greater than
20>10 = true
>=
20>=10 = true
<
Less than
20<10 = false
<=
20<=10 = false
Description
Example
&
Bitwise AND
Bitwise OR
Bitwise XOR
Bitwise NOT
(~10) = -10
<<
(10<<2) = 40
>>
(10>>2) = 2
>>>
(10>>>2) = 2
Description
Example
&&
Logical AND
||
Logical OR
Logical Not
!(10==20) = true
Example
Assign
10+10 = 20
+=
-=
*=
/=
%=
Operator
Description
(?:)
delete
in
typeof
void
yield
Operator Precedence:
Precedence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Operators
Parentheses , array subscripts or function call
!, ~, -, ++, -*, /, %
+,<<, >>, >>>
<, <=, >, >=
==, !=
&
^
|
&&
||
?:
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, |=
The operator determines which operations are evaluated before others during the parsing and
execution of complex expressions
The precedence of the operator which operations are evaluated before others during the parsing
and execution of complex expressions.
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
if(expression){
//content to be evaluated
}
Flowchart of JavaScript If statement
Lets see the example of if-else statement in JavaScript to find out the even or
odd number.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Output of the above example
a is even number
Program:
<html>
<body>
<script>
var a=20;
if(a%2==0){
if expression1 is true
if expression2 is true
if expression3 is true
if no expression is true
Program:
<html>
<body>
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
Output of the above example
a is equal to 20
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous
page. But it is convenient than if..else..if because it can be used with numbers,
characters etc.
The signature of JavaScript switch statement is given below.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Program:
<!DOCTYPE html>
<html>
<body>
<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";
}
Output of the above example
B Grade
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result+=" A Grade";
case 'B':
result+=" B Grade";
case 'C':
result+=" C Grade";
default:
result+=" No Grade";
}
document.write(result);
</script>
</body>
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
code to be executed
}
Lets see the simple example of while loop in javascript.
Program:
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=13)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
Output:
11
12
13
21
22
23
Jai
Vijay
Smith
Function Arguments
We can call function by passing arguments. Lets see the example of function
that has one argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Program:
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
Output of the above example
103 Vimal Jaiswal 30000
1) By string literal
The string literal is created using double quotes. The syntax of creating string
using string literal is given below:
var stringname="string value";
Lets see the simple example of creating string literal.
Program:
<!DOCTYPE html>
<html> <body>
<script>
var str="This is string literal";
document.write(str);
</script>
</body></html>
Output: This is string literal
var n=s1.lastIndexOf("java");
document.write(n);
</script>
Output: 16
<script>
var s1="
javascript trim
var s2=s1.trim();
document.write(s2);
</script>
";
Output:
javascript trim
Constructor
1.
2.
3.
4.
Description
getFullYear()
getMonth()
getDate()
getDay()
getHours()
getMinutes()
getSeconds()
getMilliseconds()
Program:
<html> <body>
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script> </body> </html>
OP: Current Date and Time: Thu Apr 09 2015 11:07:18 GMT+0530 (India Standard Time)
Program:
<html> <body>
Current Date and Time: <span id="txt"></span>
<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script> </body> </html>
Output: Current Time: 11:6:41
Program:
<html> <body>
Current Time: <span id="txt"></span>
<script>
window.onload=function(){getTime();}
function getTime(){
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds(); // add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
setTimeout(function(){getTime()},1000);
} //setInterval("getTime()",1000);//another way
function checkTime(i){
if (i<10){
i="0" + i;
}
return i;
} </script> </body> </html>
OP: Current Time
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given
number.
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
Program:
<!DOCTYPE html>
<html>
<body>
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
</body>
</html>
Output:
Math.random()
The JavaScript math.random() method returns the random number between 0
to 1.
Random Number is: <span id="p2"></span>
<script>
document.getElementById('p2').innerHTML=Math.random();
</script>
Output:
Random Number is: 0.8758344054222107
Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is
mn.
3 to the power of 4 is: <span id="p3"></span>
<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
</script>
Output:
3 to the power of 4 is: 81
Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given
number. For example 3 for 3.7, 5 for 5.9 etc.
Floor of 4.6 is: <span id="p4"></span>
<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script>
Output: Floor of 4.6 is: 4
Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given
number. For example 4 for 3.7, 6 for 5.9 etc.
Ceil of 4.6 is: <span id="p5"></span>
<script>
document.getElementById('p5').innerHTML=Math.ceil(4.6);
</script>
Output: Ceil of 4.6 is: 5
Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for
the given number. If fractional part is equal or greater than 0.5, it goes to upper
value 1 otherwise lower value 0.
For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
Round of 4.3 is: <span id="p6"></span><br>
Round of 4.7 is: <span id="p7"></span>
<script>
document.getElementById('p6').innerHTML=Math.round(4.3);
document.getElementById('p7').innerHTML=Math.round(4.7);
</script>
Output:
Round of 4.3 is: 4
Round of 4.7 is: 5
Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given
number. For example 4 for -4, 6.6 for -6.6 etc.
Absolute value of -4 is: <span id="p8"></span>
<script>
document.getElementById('p8').innerHTML=Math.abs(-4);
</script>
Output:
Absolute value of -4 is: 4
Window Object
1. Window Object
2. Properties of Window Object
3. Methods of Window Object
4. Example of Window Object
The window object represents a window in browser. An object of window is
created automatically by the browser.
Window is the object of browser, it is not the object of javascript. The
javascript objects are string, array, date etc.
Note: if html document contains frame or iframe, browser creates additional window
objects for each frame.
Method
Description
alert()
confirm()
displays the confirm dialog box containing message with ok and cancel
button.
prompt()
open()
close()
setTimeout() performs action after specified time like calling function, evaluating
expressions etc.
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.
Syntax
window.alert("sometext");
Example
alert("I am an alert box!");
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.
Syntax
window.confirm("sometext");
Example
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
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.
Syntax
window.prompt("sometext","defaultText");
Example
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
object.
Description
write("string")
writeln("string")
getElementById()
getElementsByName()
getElementsByTagName()
getElementsByClassName()
Enter No:
1. getElementsByName() method
2. Example of getElementsByName()
The document.getElementsByName() method returns all the element of
specified name.
The syntax of the getElementsByName() method is given below:
document.getElementsByName("name")
Here, name is required.
Example of document.getElementsByName() method
In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>
Output of the above example
Male:
Female:
1. getElementsByTagName() method
2. Example of getElementsByTagName()
The document.getElementsByTagName() method returns all the element of
specified tag name.
The syntax of the getElementsByTagName() method is given below:
document.getElementsByTagName("name")
Here, name is required.
Example of document.getElementsByTagName() method
In this example, we going to count total number of paragraphs used in the
document. To do this, we have called the
document.getElementsByTagName("p") method that returns the total
paragraphs.
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
Javascript - innerHTML
1. javascript innerHTML
2. Example of innerHTML property
The innerHTML property can be used to write the dynamic html on the html
document.
It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.
Example of innerHTML property
In this example, we are going to create the html form when user clicks on the
button.
In this example, we are dynamically writing the html form inside the div name
having the id mylocation. We are identifing this position by calling the
document.getElementById() method.
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<texta
rea rows='5' cols='80'></textarea><br><input type='submit' value='co
mment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()"
>
<div id="mylocation"></div>
</form>
Output of the above example
Next TopicJavascript innerText
Javascript - innerText
1. javascript innerText
2. Example of innerText property
The innerText property can be used to write the dynamic text on the html
document. Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as
writing the validation message, password strength etc.
Example of innerText property
In this example, we are going to display the password strength when releases
the key after press.
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()
">
Strength:<span id="mylocation">no strength</span>
</form>
Output of the above example
Strength:no strength
<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;
}
}
</script>
<form name="f1" action="register.jsp" onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" nam
e="password2"/><br/>
<input type="submit">
</form>
document.getElementById("nameloc").innerHTML="<img src='checked.gi
f'/>";
status=true;
}
if(password.length<6){
document.getElementById("passwordloc").innerHTML=
"<img src='unchecked.gif'/> Password must be at least 6 char long";
status=false;
}else{
document.getElementById("passwordloc").innerHTML="<img src='checke
d.gif'/>";
status=true;
}
return status;
}
</script>
<form name="f1" action="#" onsubmit="return validate()">
<table>
<tr><td>Enter Name:</td><td><input type="text" name="name"/
>
<span id="nameloc"></span></td></tr>
<tr><td>Enter Password:</td><td><input type="text" name="pass
word"/>
<span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td>
</tr>
</table>
</form>
Output:
Enter Name:
Enter Password:
Submit
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Description
onclick
ondblclick
onfocus
onblur
onsubmit
onmouseover
onmouseout
onmousedown
onmouseup
onload
onunload
onscroll
onresized
onreset
onkeydown
onkeypress
onkeyup