Javascript
Javascript
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>
<html>
<body>
<script language="javascript“ type="text/javascript">
document.write("welcome to javascript");
</script>
</body>
</html>
VARIABLES:
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 −
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;
== 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;
</script>
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<script type="text/javascript">
var age = 20;
else{
document.write("<b>Does not qualify for driving</b>");
}
</script>
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:
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;
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:
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 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 /> ");
if (x == 5){
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
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>
• 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>
ZaraAli
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.
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:
<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.
<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">
</body>
</html>
ADDITION OF TWO NUMBERS:
<html>
<body>
<form>
Num1: <input type="text" id="Text1">
Num2: <input type="text" id="Text2">
</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">
</script>
<body>
<script type="text/javascript">
var index = 0;
function increment(var1)
{
document.getElementById("t1").value=index;
index++;
}
</script>
• 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>
</body>
</html>
String - length Property:
<html>
<body>
<script>
</script>
</body>
</html>
Style Object:
Syntax:element.style.property
Example1:
<html>
<body>
<script>
function myFunction() {
document.getElementById("myH1").style.color = "red";
}
</script>
</body>
</html>
Style background:
Example 3
<html>
<body>
<h1>Hello World!</h1>
<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:
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:
<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>
<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
<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
<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>
<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>