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

Javascript

JavaScript is a dynamic and lightweight programming language commonly used for creating interactive web pages. It allows for the use of variables, data types, operators, control structures, and functions to build modular code. The document also covers dialog boxes for user interaction, including alert, confirmation, and prompt dialogs.

Uploaded by

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

Javascript

JavaScript is a dynamic and lightweight programming language commonly used for creating interactive web pages. It allows for the use of variables, data types, operators, control structures, and functions to build modular code. The document also covers dialog boxes for user interaction, including alert, confirmation, and prompt dialogs.

Uploaded by

jeetshah090108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

JAVASCRIPT

• JavaScript is a dynamic computer programming


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.
JavaScript can be implemented using JavaScript statements that are
placed within the <script>... </script> HTML tags in a web page.

The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.

<script>
javascript code
</script>

The script tag takes two important attributes −


• Language − This attribute specifies what scripting language you are using. Typically,
its value will be javascript.
• Type − This attribute is what is now recommended to indicate the scripting language
in use and its value should be set to "text/javascript".

<script language="javascript" type="text/javascript">


JavaScript code
</script>
Example of Javascript:

<html>
<body>
<script language="javascript“ type="text/javascript">
document.write("welcome to javascript");
</script>
</body>
</html>
VARIABLES:

1. Variables are the containers for storing information.

For example, assume you want to store two values 10 and 20 in your program and at a later stage,
you want to use these two values. Let's see how you will do it. Here are the following three simple steps −

• Create variables with appropriate names.


• Store your values in those two variables.
• Retrieve and use the stored values from the variables.

2. Javascript variables should be declare with the var statement


3. JavaScript variables are used to hold values or expressions.
4. Javascript variables are case sensitive.
5. Variable must begin with the letter.
eg: stu_name
stu_rollno
rollno
JavaScript DATATYPES
One of the most fundamental characteristics of a programming language is the set of data types it supports.
These are the type of values that can be represented and manipulated in a programming language.
data types:

Numbers: eg. 123, 120.50 etc.


Strings: of text e.g. "This text string" etc.
Boolean: e.g. true or false

Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows.
Example:
var money;
var name;
var money,name;
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.
Example: name=“john”;
money=12;
or
var name=“john”;
What is an operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the operator.
JavaScript supports the following types of operators.

Arithmetic Operators:

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
Example:
var x,y,z;
x = 5;
y = 2;
z = x + y;

Output:z=7

Example:

txt1 = "John";
txt2 = "Doe";
txt3 = txt1 + " " + txt2;

Output: John Doe


JavaScript Comparison Operators:

== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
JavaScript Logical Operators

Operator Description
&& logical and
|| logical or
! logical not
Control structures and looping:

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.

1) if..else statement.
Example
Try the following example to understand how the if statement works.

<html>
<body>

<script type="text/javascript">
var age = 20;

if( age > 18 )


{
document.write("<b>Qualifies for driving</b>");
}

</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
Example

Try the following code to learn how to implement an if-else statement in JavaScript.

<html>
<body>

<script type="text/javascript">
var age = 20;

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>
Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
<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>
The while Loop:

The purpose of a while loop is to execute a statement or code block repeatedly as long
as an expression is true. Once the expression becomes false, the loop terminates.

while (expression){
Statement(s) to be executed if expression is true
}
Example:

<html>
<body>
<script type="text/javascript">

var count = 0;
document.write("Starting Loop ");
while (count < 10)
{
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");

</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
OUTPUT:

Starting Loop Current Count : 0


Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!Set the variable to different value and then try...
The do...while Loop:

The do...while loop is similar to the while loop except that the condition check happens at the end of the loop.
This means that the loop will always be executed at least once, even if the condition is false.

do{
Statement(s) to be executed;
}
while (expression);
<html>
<body>

<script type="text/javascript">

var count = 0;

document.write("Starting Loop" + "<br />");


do{
document.write("Current Count : " + count + "<br />");
count++;
}

while (count < 5);


document.write ("Loop stopped!");
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...
FOR LOOP:
The 'for' loop is the most compact form of looping. It includes the
following three important parts −

•The loop initialization where we initialize our counter to a starting


value. The initialization statement is executed before the loop begins.
•The test statement which will test if a given condition is true or not.
If the condition is true, then the code given inside the loop will be
executed, otherwise the control will come out of the loop.
•The iteration statement where you can increase or decrease your
counter.
<html>
<body>
<script type="text/javascript">
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++)
{
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
OUTPUT:

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
The break Statement:

JavaScript provides full control to handle loops. There may be a


situation when you need to come out of a loop without reaching its
bottom. There may also be a situation when you want to skip a part of
your code block and start the next iteration of the loop.

To handle all such situations, JavaScript provides break and continuestatements. These
statements are used to immediately come out of any loop or to start the next iteration of
any loop respectively.

The break Statement


Example:
<html>
<body>
<script type="text/javascript">
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 20)


{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
OUTPUT:

Entering the loop


2
3
4
5
Exiting the loop!
Set the variable to different value and then try...
The continue Statement

The continue statement breaks one iteration (in the loop) if a specified condition occurs, and continues
with the next iteration in the loop.
The difference between continue and the break statement, is instead of "jumping out" of a loop, the
continue statement "jumps over" one iteration in the loop.
<html>
<body>

<script type="text/javascript">
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 10)


{
x = x + 1;

if (x == 5){
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}

document.write("Exiting the loop!<br /> ");


</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
OUTPUT:

Entering the loop


2
3
4
6
7
8
9
10
Exiting the loop!
Set the variable to different value and then try...
JavaScript - Functions

A function is a group of reusable code which can be called anywhere in your


program. This eliminates the need of writing the same code again and again. It
helps programmers in writing modular codes. Functions allow a programmer to
divide a big program into a number of small and manageable functions.

Function Definition

Before we use a function, we need to define it. The most common way to define a
function in JavaScript is by using the function keyword, followed by a unique
function name, a list of parameters (that might be empty), and a statement block
surrounded by curly braces.
Syntax:

<script type="text/javascript">
function functionname(parameter-list)
{
statements
}
</script>

Example:

<script type="text/javascript">

function sayHello()
{
alert("Hello there");
}

</script>
Calling a Function:
<html>
<head>

<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>

</head>
<body>
<p>Click the following button to call the function</p>

<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>

<p>Use different text in write method and then try...</p>


</body>
</html>
OUTPUT:

Click on Say Hello button


Function Parameters

• Till now, we have seen functions without parameters. But there is a facility to
pass different parameters while calling a function.
• These passed parameters can be captured inside the function and any
manipulation can be done over those parameters.
• A function can take multiple parameters separated by comma.
Example:

<html>
<head>

<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>

</head>
<body>
<p>Click the following button to call the function</p>

<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>

<p>Use different parameters inside the function and then try...</p>


</body>
</html>
OUTPUT:

Click on Say Hello button

Zara is 7 years old.


The return Statement

• A JavaScript function can have an optional return statement. This is


required if you want to return a value from a function.

• This statement should be the last statement in a function.


<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
OUTPUT:

Click on Say Hello button

ZaraAli

1) Write a program to add two numbers using function.


Dialog Box

JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise and alert, or to get confirmation on any input or to have a kind of input from the users.

Alert Dialog Box


An alert dialog box is mostly used to give a warning message to the users. For example, if
one input field requires to enter some text but the user does not provide any input, then as a
part of validation, you can use an alert box to give a warning message.

A confirmation dialog box


is mostly used to take user's consent on any option. It displays a dialog box with two buttons: Cancel and Ok
If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel
button, then confirm() returns false. You can use a confirmation dialog box as follows.
The prompt dialog box
is very useful when you want to pop-up a text box to get user input. Thus, it enables you to interact with
the user. The user needs to fill in the field and then click OK.

This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label which
you want to display in the text box and (ii) a default string to display in the text box.

This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the
window method prompt()returns null.
Alert Dialog Box

<html>
<head>

<script type="text/javascript">
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>

<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>

</body>
</html>
OUTPUT:

This is a warning message!


A confirmation dialog box
<html>
<head>
<script type="text/javascript">
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
}
else{
document.write ("User does not want to continue!");
return false;
}
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body></html>
Prompt Dialog Box
<html>
<head>

<script type="text/javascript">

function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
</script>

</head>

<body>
<p>Click the following button to see the result: </p>

<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>

</body>
</html>
Example of ALERT BOX:

<html>
<head>
<script type="text/javascript">
function add()
{
a=10;
b=20;
c=a+b;
alert(c);
}

</script>
</head>
<body>
<form>
<input type="button" value="click me" onclick="add();">
</form>

</body>
</html>
GetElementById()

• The getElementById() method returns the element that has the ID attribute with the
specified value.

• This method is one of the most common methods in the HTML DOM, and is used almost
every time you want to manipulate, or get info from, an element on your document.

• Returns null if no elements with the specified ID exists.

• An ID should be unique within a page.


To find cube of given number from text box

<html>
<body>
<script type="text/javascript">
function getcube(){
var number1=document.getElementById("number").value;
alert(number1*number1*number1);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number1"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
</body>
</html>
To display text box values:

<html>
<body>
<form>
Name: <input type="text" id="Text1">
Surname: <input type="text" id="Text2">
full name:<input type="text" id="Text3">

<p>click on button to check name and surname </p>


<button onclick="myFunction()">Try it</button>
</form>
<script>
function myFunction() {
a=document.getElementById("Text1").value;
b=document.getElementById("Text2").value;
c=a+b;
alert("full name is : " +a+ " " +b);
parseInt(document.getElementById("Text3").value)=a+" "+b;
}
</script>

</body>
</html>
ADDITION OF TWO NUMBERS:
<html>
<body>
<form>
Num1: <input type="text" id="Text1">
Num2: <input type="text" id="Text2">

<p>Click the button for addition.</p>

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


</form>
<script>
function myFunction() {
a = parseInt(document.getElementById("Text1").value);
b = parseInt(document.getElementById("Text2").value);
c = a+b;
document.write("addition of num1 and num is : " +c);
}
</script>

</body>
</html>
Write a program to print addition and subtraction using text boxes:

<html>
<head>
<body>

<script>
function add()
{
a = parseInt(document.getElementById("Text1").value);
b = parseInt(document.getElementById("Text2").value);
c = a+b;
document.getElementById("Text3").value = c;
}

function sub() {
a = parseInt(document.getElementById("Text1").value);
b = parseInt(document.getElementById("Text2").value);
c = a-b;
document.getElementById("Text4").value = c;
}
</script>
continue..
<form>
Num1: <input type="text" id="Text1">
Num2: <input type="text" id="Text2">
add: <input type="text" id="Text3">
sub :<input type="text" id="Text4">

<p>Click the button for addition.</p>

<button type="button" onclick="add();">addition</button>


<button type="button" onclick="sub();">sub</button>
</form>
</head>
</body>
</html>
<html>
<script>
function chgclr(color)
{
document.body.bgColor=color;
// in bgcolor C is capital
}

</script>

<body>

<h3> program to change background color using button </h3>

<input type="button" value="red" onclick="chgclr('red');">

<input type="button" value="green" onclick="chgclr('green');">

<input type="button" value="blue" onclick="chgclr('blue');">


</body>
</html>
Increment number by 1 using onclick event:

<script type="text/javascript">
var index = 0;

function increment(var1)
{
document.getElementById("t1").value=index;
index++;
}
</script>

<input type="button" id="button1" onclick="increment(1)" value="increment me!"/>


<input type="text" id="t1">
innerHTML:

• 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.

Example1:

<html>
<body>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
</script>
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
</body>
</html>
Example2:

<html>
<script>
function abc()
{
document.getElementById("p1").innerHTML = "CSE/IT departments";
}
</script>
<body>

<h3 id="p1"> welcome to SBMP </h3>


<input type="button" value="click" onclick="abc();">

</body>
</html>
String - length Property:

• The length property returns the length of a string (number of characters).


• The length of an empty string is 0.
• It will count the whitespaces.

<html>
<body>

<script>

var str = "this is text";


var n = str.length;
document.write("length is :" +n);

</script>

</body>
</html>
Style Object:

Syntax:element.style.property
Example1:

<html>
<body>

<h1 id="myH1">How to change the style of a header</h1>

<p>Click the button to change the style of the H1 element.</p>

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

<script>
function myFunction() {
document.getElementById("myH1").style.color = "red";
}
</script>

</body>
</html>
Style background:

Example 3

<html>
<body>

<h1>Hello World!</h1>

<button type="button" onclick="myFunction();">Set background color</button>

<script>
function myFunction() {
document.body.style.backgroundColor = "red";
}
</script>

</body>
</html>
Mouseover and mouseout event(In HTML):

<html>
<head>

<script type="text/javascript">
function over()
{
document.getElementById("t").style.visibility="hidden";
}
function out()
{
document.getElementById("t").style.visibility="visible";
}
</script>
</head>
<body>
<pre id="t" onmouseover="over()" onmouseout="out()"> hiiiiiiiiiiiii</pre>
</body>
</html>
Mouseover and mouseout event(In Javascript):

<html>
<body>
<p>This example uses the HTML DOM to assign an "onmouseover" and "onmouseout" event to a h1
element.</p>
<h1 id="demo">Mouse over me</h1>

<script>
document.getElementById("demo").onmouseover = function() {mouseOver()};
document.getElementById("demo").onmouseout = function() {mouseOut()};

function mouseOver() {
document.getElementById("demo").style.color = "red";
}

function mouseOut() {
document.getElementById("demo").style.color = "black";
}
</script>

</body>
</html>
Onblur event:

• The onblur event occurs when an object loses focus.


• The onblur event is most often used with form validation code (e.g. when the user leaves a form field).

Example:
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">

<p>When you leave the input field, a function is triggered which transforms the input text to upper
case.</p>

<script>
function myFunction() {
var x = document.getElementById("fname").value;
y = x.toUpperCase();
document.getElementById("fname").value=y;
}
</script>
</body>
</html>
Onfocus:

• The onfocus event occurs when an element gets focus


• The onfocus event is the opposite of the onblur event.

<html>
<body>
Enter your name: <input type="text" id="myInput" onfocus="focusFunction()">
<script>
function focusFunction()
{
// Focus = Changes the background color of input to yellow
document.getElementById("myInput").style.background = "yellow";
}

</script>
</body>
</html>
Onfocus - onblurr event

<html>
<body>

Enter your name: <input type="text" id="myInput" onfocus="focusFunction()" onblur="blurFunction()">

<script>
function focusFunction() {
// Focus = Changes the background color of input to yellow
document.getElementById("myInput").style.background = "yellow";
}

function blurFunction() {
// No focus = Changes the background color of input to red
document.getElementById("myInput").style.background = "red";
}
</script>

</body>
</html>
onsubmit event

The onsubmit event occurs when a form is submitted.

<html>
<body>

<p>When you submit the form, a function is triggered which alerts some text.</p>

<form onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

<script>
function myFunction() {
alert("The form was submitted");
}
</script>

</body>
</html>
onreset event

• The onreset event occurs when a form is reset.

<html>
<body>

<p>When you reset the form, a function is triggered which alerts some text.</p>

<form onreset="myFunction()">
Enter name: <input type="text">
<input type="reset">
</form>

<script>
function myFunction() {
alert("The form was reset");
}
</script>

</body>
</html>
onselect Event

• The onselect event occurs after some text has been selected in an element.
• The onselect event is mostly used on <input type="text"> or <textarea>
elements.

<html>
<body>

Select some of the text: <input type="text" value="Hello world!"


onselect="myFunction()">

<script>
function myFunction()
{
alert("You selected some text!");
}
</script>

</body>
</html>
FORM VALIDATION USING FORM NAME.

<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (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="get" action="hi.html" onsubmit="return validateform()">
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
FORM VALIDATION USING getElementById() method

<script>
function validateform(){
var name1=document.getElementById("t1").value;

if (name1=="")
{
alert("enter valid");
}
else
{
alert("successfull");
}}
</script>
<body>
<form name="myform" method="post" >
Name: <input type="text" id="t1"><br/>
<input type="submit" value="register" onclick="validateform()">
</form>
</body>

You might also like