Java Script

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 15

JavaScript

1. Script is a set of instruction used to perform certain task either on server side or client side.
2. JavaScript is a subset of java.

Scripting Languages Types

Client Side Server Side


Examples Examples
1. JavaScript. 1. PHP.
2. VBScript. 2. .NET.
3. Jscript. 3. JAVA.
4. WML Script. 4. Ruby on rails.
e..t.c e..t.c

Variable
It is a data name to store a data value. Example var a;

Initialization
Giving value to variable is called as Initialization. Example a=10;

<html>
<body>
<h2>Addition</h2>
<p id="demo"></p>
<script>
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
document.getElementById("demo").innerHTML
="The value of z is " + z + ".";
</script>
</body>
</html>

Operators
Arithmetic Operators
Operator Description Operator Description
+ Addition % Modulus (Remainder)
- Subtraction ++ Increment
* Multiplication -- Decrement
/ Division

Wisdom Materials 1
Operators
Assignment Operators Logical Operators Comparison Operators
Operator Example Same As Operato Description Operato Description
r r
= x=y x=y && logical and == equal to
+= x += y x=x+y || logical or != not equal
-= x -= y x=x–y ! logical not > greater than
*= x *= y x=x*y < less than
/= x /= y x=x/y >= greater than or equal to
%= x %= y x=x%y <= less than or equal to
?: ternary operator

Comments
1. Single line comments----//.
2. Multiline Comments---- /* and */.
3. Comments are not executed.

Conditional Statements and Kinds of loops


Conditional Statements Kinds of Loops
If if (condition) { Code } For For(declaration;condition;increment/Decrement)
{ code}
For(int i=1;i<10;1++)
{code}
Else if (condition) { code } While while (condition) { code }
else { code }
Else if if (condition1) { code } Do Do{ code} while(Condition)
else if (condition2) { code } while
else {code }
switch switch(expression)
{
case n: code block; break;
case n: code block; break;
default: code block; break;
}

Break Statement
It is used to come out of a loop completely and continues executing the code after the loop (if
any).

Continue Statement
It breaks one iteration (in the loop), if a specified condition occurs, and continues with the next
iteration in the loop.

Function
It is a set of instructions used to perform a particular task.
Wisdom Materials 2
Example
<html>
<script>
function hai() { window.alert("hi"); }
</script>
<body>
<input type="button" value="click me" onclick="hai();"/>
</body>
</html>

Text Box
<html>
<head><title>Validation-TextBox</title>
</head>
<script language="javascript" type="text/javascript">
function Validate()
{
var t1=document.f1.t1.value;
if (t1.length == 0) { alert('Please enter details in textbox1');
return false; }
else { alert(t1); return true; }

}
</script>
<body>
TextBox
<form name="f1" onsubmit="return Validate()"
action="http://www.google.com/" method="post" >
<table border="1">
<tr>
<td>username</td>
<td><input type="text" name="t1" id="fname" /></td>
</tr>

<tr>
<td><input type="reset" value="reset" name="reset" /></td>
<td><input type="submit" value="submit" name="submit"
/></td>
</tr>

</table>
</form>
</body>
</html>

Wisdom Materials 3
Radio
<html>
<head><title>Validation-Radio</title>
</head>
<script language="javascript" type="text/javascript">
function Validate()
{
if (document.f1.r1.checked == true)
{
alert("Radio Butoon Value: "+document.f1.r1.value); return true;
}

else if (document.f1.r2.checked == true)


{
alert("Radio Butoon Value: " + document.f1.r2.value);
return true;
}
else {
alert("Please select a radio button"); return false;
}
}
</script>
<body>
Radio
<form name="f1" onsubmit="return Validate()"
action="http://www.google.com/" method="post" >
<table border="1">

<tr>
<td>Gender</td>
<td>
<input type="radio" id="r1" name="gender" value="male" />male
<input type="radio" id="r2" name="gender"
value="female"/>female
</td>
</tr>

<tr>
<td><input type="reset" value="reset" name="reset" /></td>
<td><input type="submit" value="submit" name="submit" /></td>
</tr>

</table>
</form>
</body>
</html>

Wisdom Materials 4
Select
<html>
<head><title>Validation-Select</title>
</head>
<script language="javascript" type="text/javascript">
function Validate()
{
var yearvalue = document.f1.year.value;
alert("selected Value" + yearvalue);
if (yearvalue == 0) {
alert("Please select a Value"); return false;
}
else {
alert("Select Value"+document.f1.year.value);
return true;
}

}
</script>
<body>
Select
<form name="f1" onsubmit="return Validate()"
action="http://www.google.com/" method="post" >
<table border="1">

<tr>
<td>Year</td>
<td><select name="year">
<option value="0">Select</option>
<option value="1">Year1</option>
<option value="2">Year2</option>
<option value="3">Year3</option>
<option value="4">Year4</option>
</select></td>
</tr>

<tr>
<td><input type="reset" value="reset" name="reset" /></td>
<td><input type="submit" value="submit"
name="submit" /></td>
</tr>

</table>
</form>
</body>
</html>

Wisdom Materials 5
Gmail
<html>
<head><title>Validation-Gmail</title>
</head>
<script language="javascript" type="text/javascript">
function Validate()
{
var t1 = document.f1.t4.value;
if (t1.match("@gmail.com"))
alert(t1);
}
</script>
<body>
Gmail
<form name="f1" onsubmit="return Validate()"
action="http://www.google.com/" method="post" >
<table border="1">

<tr>
<td>Email</td>
<td><input type="text" name="t4"
id="email2"/></td>
</tr>

<tr>
<td><input type="reset" value="reset" name="reset"
/></td>
<td><input type="submit" value="submit"
name="submit" /></td>
</tr>
</table>
</form>
</body>
</html>

Object
1. It is a real world thing or entity.
Object. Method Name(Parameters); Object. Property name=value;

JavaScript Objects
S.No Object Name S.No Object Name
1 Window 6 Arrays
2 Document 7 Date
3 String 8 Math
4 Console
5 Number

Wisdom Materials 6
Window Properties
screenX Returns the horizontal coordinate of the window relative to the screen
screenY Returns the vertical coordinate of the window relative to the screen

Window Methods
open() window.open("https://www.w3schools.com"); Open a new window.
prompt window.prompt("Enter no1") Asks for data as input.
alert window.prompt("Enter no1") Displays the data.
close() window.close(); close the current window.

Example
<html>
<head><title>Addition Program</title>
</head>
<script language="javascript" type="text/javascript">
function add() {
var n1=parseInt(window.prompt("Enter no1"));
var n2=parseInt(window.prompt("Enter no2"));
var n3 = n1+n2;
window.alert("sum"+n3);
}
</script>
<body>
<form name="f1" >
<input type="button" value="Add" name="Add"
onclick="add();" />
</body>
</html>

Document Properties
bgColor document.bgColor =”blue”;
document.body.style.backgroundColor document.body.style.backgroundColor="blue";
document.fgColor document.fgColor = "yellow";
Document.linkColor Document.linkColor="yellow";

Document Methods
Write() Writes HTML expressions or JavaScript code to a document
writeln() Same as write(), but adds a newline character after each statement

Wisdom Materials 7
Example: 1. Write a program to add 2 numbers.
<html>
<head><title>Addition Program</title>
</head>
<script language="javascript" type="text/javascript">
function Validate() {
var t1 = parseInt(document.f1.t1.value);
var t2 = parseInt(document.f1.t2.value);
document.f1.t3.value = (t1 + t2).toString();
}
</script>
<body>

<form name="f1" >


Addition Program
<table border="1">

<tr><td>username</td>
<td><input type="text" name="t1" id="n01" /></td>
</tr>

<tr><td>password</td>
<td><input type="text" name="t2" id="n02" /></td>
</tr>

<tr><td>Result</td>
<td><input type="text" name="t3" id="n03" /></td>
</tr>

<tr>
<td><input type="reset" value="reset" name="reset" /></td>
<td><input type="button" value="Add" name="Add"
onclick="Validate();" /></td>
</tr>
</table>
</form>
</body>
</html>

2. Write a program to display some text dynamically.


<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML =
"JavaScript changed.";

Wisdom Materials 8
}
</script>
</head>
<body>
<p id="demo">JavaScript Text.</p>
<button type="button" onclick="myFunction()">Click
me</button>
</body>
</html>
document.getElementById("demo").style.fontSize = "35px";

Example
<html>
<body>
<h1>Add Numbers</h1>
<h1>5+5</h1>
<button type="button" onclick="document.write(5 + 5)">Try
it</button> 10
</body>
</html>

String
1. It is a collection of characters.
2. It can be any text inside double or single quotes.
Example: var mystr = "abcd 1234";

String Properties and Methods


length Returns the length of a string
Var a = parseInt(textboxname.length);
Example
document.f1.t4.value = parseInt(t1.length);
String Methods
Method Description
charAt() Returns the character at the specified index (position)
concat() Joins two or more strings, and returns a new joined strings
endsWith() Checks whether a string ends with specified string/characters
includes() Checks whether a string contains the specified string/characters
indexOf() Returns the position of the first found occurrence of a specified value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
match() Searches a string for a match against a regular expression, and returns the matches
replace() Searches a string for a specified value, or a regular expression, and returns a new
string where the specified values are replaced
search() Searches a string for a specified value, or regular expression, and returns the
position of the match
split() Splits a string into an array of substrings
startsWith() Checks whether a string begins with specified characters
substr() Extracts the characters from a string, beginning at a specified start position, and

Wisdom Materials 9
through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string

String Operations
text1 = "John"; text2 = "Doe"; text3 = text1 + " " + text2;

<html> abcd
<body>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "ab",
lastName : "cd",
id : 1234,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML
= person.fullName();
</script>
</body></html>
Upper and Lower Case
String. toUpperCase(); String. toLowerCase();
charAt() Method
var str = "HELLO WORLD"; str.charAt(0);

Number Object
<html>
<body>
<h2>Adition Program</h2>
<p id="demo"></p>
<script>
var x = 123; Methods
var y = new Number(123); 1.toString()
document.getElementById("demo").innerHTML 2. toExponential(2)
= x+y; 3. toFixed(0)
</script> 4. toPrecision()
</body>
</html>

Wisdom Materials 10
Console log()

Converting Variables to Numbers


Method Description
Number() Returns a number, converted from its argument.
parseFloat() Parses its argument and returns a floating point number
parseInt() Parses its argument and returns an integer

Arrays
It collections of element all are of same data type.
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var abcd = ["ab", "cd", "ef"];
document.getElementById("demo").innerHTML =
abcd;
</script>
</body>
</html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var abcd = ["ab", "cd", "ef"];
document.getElementById("demo").innerHTML =
abcd[0];
</script>
</body>
</html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
var abcd = ["ab", "cd", "ef"];
document.getElementById("demo").innerHTML =
abcd;
</script>
</body>
</html>

Wisdom Materials 11
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
var person = {firstName:"abcd", lastName:"1234",
age:99};
document.getElementById("demo").innerHTML =
person["firstName"];
</script>
</body>
</html>

Array Elements Can Be Objects


myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods


var x = cars.length; // The length property returns the number of elements
var y = cars.sort(); // The sort() method sorts arrays
The length Property
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4

<html>
<body>
<p>The length property returns the length of an
array.</p>
<p id="demo"></p>
<script>
var fruits = ["a", "b", "c", "d"];
document.getElementById("demo").innerHTM
L = fruits.length;
</script>
</body>
</html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>Array alphabetically or numerically.</p>
<button onclick="myFunction1()">Sort
Alphabetically</button>
<button onclick="myFunction2()">Sort
Numerically</button>

Wisdom Materials 12
<p id="demo"></p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTM
L = points;

function myFunction1() {
points.sort();

document.getElementById("demo").innerHTM
L = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTM
L = points;
}
</script>
</body>
</html>

Date
<html>
<body>
<h2>JavaScript Date Object</h2>
<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>
<p id="demo4"> </p>
<p id="demo5"> </p>
<script>
var d = new Date();
document.getElementById("demo1").innerHTML = "Year:
"+d.getFullYear();
document.getElementById("demo2").innerHTML = "Year:
"+d.getDate();
document.getElementById("demo3").innerHTML = "Month: "+
d.getMonth();
document.getElementById("demo4").innerHTML ="Minutes:"+
d.getMinutes();
document.getElementById("demo5").innerHTML ="Seconds:
"+d.getSeconds();
</script>
</body>
</html>

Wisdom Materials 13
Math Object
Math.PI; Math.abs(-4.7); Math.cos(0 * Math.PI / 180);
Math.round(4.4); Math.ceil(4.4); Math.min(0, 150, 30, 20, -8, -200);
Math.pow(8, 2); Math.floor(4.7); Math.max(0, 150, 30, 20, -8, -200);
Math.sqrt(64); Math.sin(90 * Math.PI / 180); Math.random(); 0-1
Math.E // returns Euler's number Math.LN10 // returns the natural logarithm of 10
Math.PI // returns PI Math.LOG2E // returns base 2 logarithm of E
Math.SQRT2 // returns the square root of 2 Math.LOG10E // returns base 10 logarithm of E
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2

Math Object Methods


Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y, x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns the value of x rounded up to its nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns the value of x rounded down to its nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x, y, z, ..., n) Returns the number with the highest value
min(x, y, z, ..., n) Returns the number with the lowest value
pow(x, y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Returns the value of x rounded to its nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

Boolean
<html>
<body><p>Boolean</p>
<button onclick="myFunction()">click it</button>
<p id="demo"></p>
<script>
function myFunction() { var x = -0;
document.getElementById("demo").innerHTML = Boolean(x);
}
</script>
</body>
</html>
Events

Wisdom Materials 14
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

Escape sequences
Code Result
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator

Wisdom Materials 15

You might also like