0% found this document useful (0 votes)
20 views

Javascript

Uploaded by

Sourav Padhan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Javascript

Uploaded by

Sourav Padhan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

JAVASCRIPT

What is JavaScript
 JavaScript is very easy to implement because it
is integrated with HTML. It is open and cross-
platform.
 JavaScript is used to create client-side dynamic
pages.
 JavaScript is an object-based scripting
language which is lightweight and cross-platform.
 JavaScript is not a compiled language, but it is a
translated language. The JavaScript Translator
(embedded in the browser) is responsible for
translating the JavaScript code for the web
browser.
Applications of Javascript

 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog
boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
 Displaying clocks etc.
JavaScript Example

<html>
<head></head>
<body>
<script>
document.write("Hello JavaScript ");
</script>
</body>
</html>
External JavaScript

Jvsc.html

mmm.js <html>
<head>
<script type="text/
function msg(){ javascript" src="mmm.js"></
script>
alert("Hello Javatpoin </head>
t"); <body>
<p>Welcome to cs family</p>
} <form>
<input type="button" value="click"
onclick="msg()"/>
</form>
</body>
</html>
JavaScript popup Box
 JavaScript has three kind of popup boxes: Alert box,
Confirm box, and Prompt box.
 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 of alert box
 <html>
 <body>

 <h2>JavaScript Alert</h2>

 <button onclick="myFunction()">Try it</button>

 <script>
 function myFunction() {
 alert("I am an alert box!");
 }
 </script>

 </body>
 </html>
 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");
<html>
example
<head>
<script type=“text/javascript”>
Fuction show_confirm()
{
Var r=confirm(“press a button”);
If(r==true)
{
alert(“you pressed ok!”);
}
Else
{
Alert(“cancel”);
}
}
</script>
</head>
<body>
<input type=“button” onclick=“show_confirm()” value=“confirm”>
</body>
</html>
 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
<html>
<head>
<script type=“text/javascript”>
Fuction show_prompt()
{
Var r=prompt(“enter name”,”harry”);
If(r!=null && r!=“”)
{
Document.write(“hello”+ r+”how are you?”);
}
}
</script>
</head>
<body>
<input type=“button” onclick=“show_prompt()” value=“promptbox”>
</body>
</html>
JavaScript Variables

 Variables are Containers for Storing Data


 JavaScript Variables can be declared in 4
ways:
 Automatically
 var
 let
 const
Rules of 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).
 Name must start with a letter (a to z or A to Z),
underscore( _ ), or dollar( $ ) sign.
 After first letter we can use digits (0 to 9), for
example value1.
 JavaScript variables are case sensitive, for
example x and X are different variables.
automatically
<html>
<body>
<h1>JavaScript Variables</h1>

<p>They are automatically declared when first used.</p>

<p id="demo"></p>

<script>
x = 5;
y = 6;
z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>
Var example
 <html>
 <body>
 <script>
 var x = 10;
 var y = 20;
 var z=x+y;
 document.write(z);
 </script>
 </body>
 </html>
Let example
<html>
<body>

<h2>Variable Using let</h2>

<p id="demo"></p>

<script>
let x ,y,z;
x=parseInt(prompt("enter first number",""));
y=parseInt(prompt("enter second number",""))
z=x+y;

document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>
Const example
<html>
<body>
<h1>JavaScript Variables</h1>

<p>hgjhgjhkjkjlj.</p>
<p id="demo"></p>
<script>
const x = 5;
const y = 6;
const z = x + y;
document.getElementById("demo").innerHTML ="The value of z is: " +
z;
</script>
</body>
</html>
Conditional statement
 JavaScript If-else
 The JavaScript if-else statement is
used to execute the code whether
condition is true or false. There are three
forms of if statement in JavaScript.
 If Statement
 If else statement
 if else if statement
Example of if-else
<html>
<body>
<script>
var a=20;
if(a>10)
{
document.write("value of a is greater than 10");
}
</script>
</body>
</html>
If-else
<html>
<body>
<script>
var a=20;
if(a%2==0)
{
document.write("a is even number");
}
Else
{
document.write("a is odd number");
}
</script>
</body>
</html>
Switch statement
 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.
syntax
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;
}
If-else-if
<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>
syntax
<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";
}
document.write(result);
</script>
</body>
</html>
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.
 for loop
 while loop
 do-while loop
 for-in loop
The JavaScript for loop iterates the
elements for the fixed number of times. It
should be used if number of iteration is
known.
for (initialization; condition; increment)
{
code to be executed
}
For loop example
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
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.
while (condition)
{
code to be executed
}
example
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Do while loop
 The JavaScript do while loop iterates
the elements for the infinite number of
times like while loop. But, code
is executed at least once whether
condition is true or false.
do{
code to be executed
}while (condition);
example
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body></html>
JavaScript Functions

 JavaScript functions are used to perform operations. We


can call JavaScript function many times to reuse the code.
 Advantage of JavaScript function
 There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so
it save coding.
2. Less coding: It makes our program compact. We don’t
need to write many lines of code each time to perform a
common task.
3. Syntax:-
 function functionName([arg1, arg2, ...argN]){
 //code to be executed
 }
example

<html>
<body>
<script>
function msg()
{
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
JavaScript Function Arguments

<script>
function product(n1 , n2){
alert(n1*n2);
}
</script>
<form>
<input type="button" value="click" onclick
=“product(4,3)"/>
</form>
Function with Return Value

script>
function hhh(){
return "hello ! How r u?";
}
</script>
<script>
document.write(hhh());
</script>
JavaScript Function Object

In JavaScript, the purpose of Function


constructor is to create a new Function object. It
executes the code globally. However, if we call the
constructor directly, a function is created
dynamically but in an unsecured way.
example
<script>
var add=new Function("n1","n2","return n1
+n2");
document.writeln(add(2,5));
</script>
JavaScript Array

 JavaScript array is an object that represents a


collection of similar type of elements.
 There are 3 ways to construct array in JavaScript
 By array literal
 By creating instance of Array directly (using new
keyword)
 By using an Array constructor (using new
keyword)
1) JavaScript array literal

 var arrayname=[value1,value2.....valueN];
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br/>");
}
</script>
2) JavaScript Array directly (new keyword)
Syntax:-
var arrayname=new Array();
Example:-
<script>
var i;
var emp = new Array();
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)

 <script>
 var emp=new Array("Jai","Vijay","Smith");

 for (i=0;i<emp.length;i++){
 document.write(emp[i] + "<br>");
 }
 </script>
Browser Object Model

 The Browser Object Model (BOM) is


used to interact with the browser.
 The default object of browser is window
means you can call all the functions of
window by specifying window or directly.
 Example:-
 window.alert("hello javascript");
 Is same as
 alert("hello javascript");
Document Object Model

 The document object represents the whole


html document.
 When html document is loaded in the browser, it
becomes a document object. It is the root
element that represents the html document. It
has properties and methods. By the help of
document object, we can add dynamic content
to our web page.
Properties of document object
Methods of document object
Method Description

write("string") writes the given string on the


doucment.
writeln("string") writes the given string on the
doucment with newline character
at the end.
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.
Accessing field value by document
object

 we are going to get the value of input text by


user. Here, we are
using document.form1.name.value to get the
value of name field.
 Here, document is the root element that
represents the html document.
 form1 is the name of the form.
 name is the attribute name of the input text.
 value is the property, that returns the value of
the input text.
example
 <script type="text/javascript">
 function printvalue(){
 var name=document.form1.name.value;
 alert("Welcome: "+name);
 }
 </script>

 <form name="form1">
 Enter Name:<input type="text" name="name"/>
 <input type="button" onclick="printvalue()" value=
"print name"/>
 </form>
Javascript - document.getElementById() method

 The document.getElementById() method returns the element of


specified id.
 we can use document.getElementById() method to get value of the
input text. But we need to define id for the input field.

 <script type="text/javascript">
 function getcube(){
 var number=document.getElementById("number").value;
 alert(number*number*number);
 }
 </script>
 <form>
 Enter No:<input type="text" id="number" name="number"/
><br/>
 <input type="button" value="cube" onclick="getcube()"/>
 </form>
GetElementsByClassName()

 The getElementsByClassName() method is


used for selecting or getting the elements
through their class name value.
 This DOM method returns an array-like
object that consists of all the elements
having the specified classname.
 On calling the getElementsByClassName()
method on any particular element, it will
search the whole document and will return
only those elements which match the
specified or given class name.
example
 <html>
 <head> <h5>DOM Methods </h5> </head>
 <body>
 <div class="Class">
 This is a simple class implementation
 </div>
 <script type="text/javascript">
 var x=document.getElementsByClassName('Class');
 document.write(“This is a method which is used in
javascript : <br>"+x);
 </script>
 </body>
 </html>
document.getElementsByName() method
 The document.getElementsByName()
method returns all the element of
specified name.
 Syntax:-
 document.getElementsByName("name")
example
 <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="femal


e">

 <input type="button" onclick="totalelements()" value="To


tal Genders">
 </form>
document.getElementsByTagName() method
 The document.getElementsByTagName() method returns
all the element of specified tag name.

 <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>
 <p>Here we are going to count total number of paragraphs
by getElementByTagName() method.</p>
 <p>Let's see the simple example</p>
 <button onclick="countpara()">count paragraph</
button>
 <html>
Javascript - innerHTML
 <body>
 <script type="text/javascript" >
 function showcommentform() {
 var data="Name:<br><input type='text'
name='name'><br>Comment:<br><textarea rows='5'
cols='50'></textarea><br><input type='submit' value='submit'>";

 document.getElementById('mylocation').innerHTML=data;
 }

 </script>
 <form name="myForm">
 <input type="button" value="comment"
onclick="showcommentform()">
 <div id="mylocation"></div>
 </form>
 </body>
 </html>
JavaScript Form Validation

 It is important to validate the form


submitted by the user because it can
have inappropriate values. So, validation
is must to authenticate user.
 JavaScript provides facility to validate the
form on the client-side so data processing
will be faster than server-side validation.
Most of the web developers prefer
JavaScript form validation.
example
 <script>
 function validateform(){
 var name=document.myform.name.value;
 var password=document.myform.password.value;

 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;
 }
 }
 </script>
 <body>
 <form name="myform" method="post" action="abc.jsp" onsubmit="return valid
ateform()" >
 Name: <input type="text" name="name"><br/>
 Password: <input type="password" name="password"><br/>
 <input type="submit" value="register">
 </form>

You might also like