Css All CH Notes
Css All CH Notes
Advantages of JavaScript
Speed: Client-side JavaScript is very fast because it can be run immediately within the
client-side browser.
Simplicity: JavaScript is relatively simple to learn and implement.
Popularity: JavaScript is used everywhere on the web.
Interoperability: JavaScript plays nicely with other languages and can be used in a huge
variety of applications.
Server Load: Being client-side reduces the demand on the website server.
Gives the ability to create rich interfaces.
Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors
Increased interactivity − You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
Client side scripts may also have some instructions for the web browser to follow in response to
certain user actions, such as pressing a page button. They can often be looked if client want to
view the source code of web page.
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming
You can place the <script> tags, containing your JavaScript, anywhere within your web page, So the identifiers Time and TIME will convey different meanings in JavaScript.
but it is normally recommended that you should keep it within the <head> tags.
Comments in JavaScript
The <script> tag alerts the browser program to start interpreting all the text between these
JavaScript supports both C-style and C++-style comments, Thus −
tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...> Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript code JavaScript.
</script> Any text between the characters /* and */ is treated as a comment. This may span
The script tag takes two important attributes − multiple lines.
1. Language − This attribute specifies what scripting language you are using. Typically, its Example
value will be javascript. Although recent versions of HTML (and XHTML, its successor) The following example shows how to use comments in JavaScript.
have phased out the use of this attribute. <script language = "javascript" type = "text/javascript">
// This is a comment. It is similar to comments in C++
2. Type – This attribute tells the browser that script is in plain text and text is organised in /*
the format of javascript. This is a multi-line comment in JavaScript
So your JavaScript segment will look like − It is very similar to comments in C Programming
<script language = "javascript" type = "text/javascript"> */
</script>
JavaScript code
</script>
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming
Script in <body>...</body> section. You can put your JavaScript code in <head> and <body> section altogether as follows −
<html>
Script in <body>...</body> and <head>...</head> sections.
<head>
Script in an external file and then include in <head>...</head> section. <script type = "text/javascript">
In the following section, we will see how we can place JavaScript in an HTML file in different
ways. function sayHello()
{
a) JavaScript in <head>...</head> section alert("Welcome to spc World")
}
If you want to have a script run on some event, such as when a user clicks somewhere, then you </script>
will place that script in the head as follows − </head>
<html>
<head> <body>
<script type = "text/javascript">
function sayHello() <script type = "text/javascript">
{
alert("WELCOME TO spc World") document.write("Hello World")
}
</script> </script>
</head>
<body> <input type = "button" onclick = "sayHello()" value = "Say
<input type = "button" onclick = "sayHello()" value = "Say Hello"/> Hello" />
</body> </body>
</html> </html>
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming
As you begin to work more extensively with JavaScript, you will be likely to find that there are
cases where you are reusing identical JavaScript code on multiple pages of a site.
JavaScript Variables
You are not restricted to be maintaining identical code in multiple HTML files. The script tag JavaScript includes Variables which are defined as named memory locations. Variable stores a
provides a mechanism to allow you to store JavaScript in an external file and then include it into single data value that can be changed later.
your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code Variable Declaration:
using script tag and its src attribute. Before you use a variable in a JavaScript program, you must declare it.
<html> Variables are declared with the var keyword as follows.
<head>
<script type = "text/javascript" src = <script type = "text/javascript">
"C:\Users\Akshay\Desktop\akshay.js"> var money;
</script> var name;
</head> </script>
<body> You can also declare multiple variables with the same var keyword as follows −
<input type = "button" onclick = "sayHello()" value = "Say
Hello" /> <script type = "text/javascript">
</body> var money, name;
</html> </script>
</script>
Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data
type. Unlike many other languages, you don't have to tell JavaScript during variable declaration
what type of value the variable will hold. The value type of a variable can change during the
execution of a program and JavaScript takes care of it automatically.
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming
1. You should not use any of the JavaScript reserved keywords as a variable name. For example, The non-primitive data types are as follows:
break or boolean variable names are not valid. - Object
- Array
2. JavaScript variable names should not start with a numeral (0-9). - RegExp
They must begin with a letter or an underscore character.
For example, 123test is an invalid variable name but _123test is a valid one.
3. JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming
1.3 Objects Hence, each object has its own set of properties. An object can be created with curly
brackets {...} with list of properties.
Real Life Objects, Properties, and Methods
A property is a "key: value pair, where key is a string (also called a "property name"), and
In real life, a car is an object.
value can be anything.
A car has properties like weight and color, and methods like start and stop:
car.color = white car.stop() This is the easiest way to create a JavaScript Object. Using an object literal, you both define and
create an object in one statement. An object literal is a list of name:value pairs inside curly
All cars have the same properties, but the property values differ from car to car. All cars have braces {}.
the same methods, but the methods are performed at different times.
The following example creates a new JavaScript object with four properties:
A] JavaScript Objects syntax :
object={property1:value1,property2:value2...... propertyN:valueN}
JavaScript is an object-based language. Everything is an object in JavaScript. As you can see, property and value is separated by : (colon).
All primitive data types can contain only a single thing (either a string or a number). In Example:
contrast, objects are used to store collections of data and more complex entities. <script>
JavaScript objects are collections of properties and methods. emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
A property is a value or set of values that is a member of an object </script>
A method is a function that is a member of an object.
Spaces and line breaks are not important. An object definition can span multiple lines:
Objects in JavaScript may be defined as, an unordered collection of related data of <script>
primitive or reference types in the form of "key: value" pairs, emp= {
You access an object's properties and methods by using the dot syntax along with the id:102,
object name and its property or method. name:"Shyam Kumar",
salary:40000
B] Object Name }
Each object is uniquely identified by a name or ID. document.write(emp.id+" "+emp.name+" "+emp.salary);
A web page contains many objects, some of which are the same kind of object. These objects </script>
can be easily distinguishable by using its name or ID.
2. Using the JavaScript Keyword new
C] Property
A property is a data or value associated with an object. Syntax:
Objects can have many data's associated with them depending on application of use.
var objectname=new Object();
For example, a form object can have a title, a width and a height as properties whereas a
window object can have a background color, a width and height as properties.
Here, new keyword is used to create object.
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming
In the following code user object is created with two properties: The this Keyword
1 The first property has the name fname and the value "Computer" In a function definition, this refers to the "owner" of the function.
2. The second one has the name lname and the value "Engineering". In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.
Example:
<html>
<head>
<title>Object</title>
</head>
<body>
<script>
var user = {
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming
JavaScript supports the following types of operators. Sr. Operator & Description Example
2 - (Subtraction): Subtracts the second operand from the first Ex: A - B will give -10 /= (Divide and Assignment)
Ex: C /= A is equivalent to
5 It divides the left operand with the right operand and assigns
C=C/A
3 * (Multiplication): Multiply both operands Ex: A * B will give 200 the result to the left operand.
4 / (Division): Divide the numerator by the denominator Ex: B / A will give 2 %= (Modules and Assignment)
Ex: C %= A is equivalent
6 It takes modulus using two operands and assigns the result to
5 % (Modulus): Outputs the remainder of an integer division Ex: B % A will give 0 to C = C % A
the left operand.
6 ++ (Increment): Increases an integer value by one Ex: A++ will give 11 Ex. C**=A is equivalent to
7 **=
C=C*A
7 -- (Decrement): Decreases an integer value by one Ex: A-- will give 9
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming
Output
Qualifies for driving
2) if...else statement
Syntax
if (expression)
{
Statement(s) to be executed if expression is true
}
else
{
Statement(s) to be executed if expression is false
JavaScript supports the following forms of if..else statement − }
if statement
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
if...else statement the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
if...else if... statement. block are executed.
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Example Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<!DOCTYPE html>
<body>
<html>
<script type = "text/javascript">
<head>
var age = 15;
<title>First Page</title>
<script type = "text/javascript">
if( age > 18 )
{
var m1=30,m2=40,m3=35,m4=34,m5=30;
document.write("<b>Qualifies for driving</b>");
var total=m1+m2+m3+m4+m5;
}
var per=total/5
else
document.write("Total is "+total)
{
document.write("<br>")
document.write("<b>Does not qualify for driving</b>");
document.write("Percentage is "+per)
}
document.write("<br>")
</script>
</body>
if(per>70)
</html>
{
document.write("Distinction")
Output }
Does not qualify for driving
else if(per>60)
3) if...else if... statement {
document.write("First Class")
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct }
decision out of several conditions. else if(per>50)
{
Syntax document.write("Second Class")
}
The syntax of an if-else-if statement is as follows −
else if(per>40)
if (expression 1)
{
{
document.write("Pass")
Statement(s) to be executed if expression 1 is true
}
}
else
else if (expression 2)
{
{
document.write("Fail")
Statement(s) to be executed if expression 2 is true
}
}
else if (expression 3)
{
</script>
Statement(s) to be executed if expression 3 is true
</head>
}
<body>
else
</body>
{
</html>
Statement(s) to be executed if no expression is true
}
It is just a series of if statements, where each if is a part of the else clause of the previous
statement. Statement(s) are executed based on the true condition, if none of the conditions is
true, then the else block is executed.
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
4) nested if else statement B) switch statement
Nested if statements mean if statement inside another if statement. The JavaScript switch statement is used in decision making.
Syntax: The switch statement evaluates an expression and executes the corresponding body that
if (condition1) matches the expression's result.
{ Syntax:
// Executes when condition1 is true switch (variable/expression)
if (condition2) {
{
case value1:
// Executes when condition2 is true
} // body of case 1
} break;
case value2:
Example: // body of case 2
<!DOCTYPE html> break;
<html> case valueN:
<head> // body of case N
<title>Nested If Else</title> break;
<script type="text/javascript"> default:
var a=10,b=40,c=30; // body of default
if(a>b) }
{
if(a>c) The switch statement evaluates a variable/expression inside parentheses ().
{ If the result of the expression is equal to value1, its body is executed.
document.write("Largest number is "+a) If the result of the expression is equal to value2, its body is executed.
}
This process goes on. If there is no matching case, the default body executes.
else
{
Notes:
document.write("largest number is "+c)
The break statement is optional. If the break statement is encountered, the switch statement
}
ends.
}
If the break statement is not used, the cases after the matching case are also executed.
else
The default clause is also optional.
{
if(b>c)
{ Flowchart:
document.write("Largest number is "+b)
}
else
{
document.write("Largest number is "+c)
}
}
</script>
</head>
<body>
</body>
</html>
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Example: Example 2
<html> <!DOCTYPE html>
<body> <html>
<script type = "text/javascript"> <head>
var grade = 'd'; <title>Switch</title>
document.write("Entering switch block<br />"); <script type = "text/javascript">
switch (grade) {
case 'A': document.write("Good job<br />");
var operator = '+';
break;
var number1=23,number2=10,result;
case 'B': document.write("Pretty good<br />");
document.write("Entering switch block<br />");
break;
case 'C': document.write("Passed<br />"); switch(operator)
break; {
case 'D': document.write("Not so good<br />"); case '+':
break; result = number1 + number2;
case 'E': document.write("Failed<br />"); document.write(result)
break; break;
default: document.write("Unknown grade<br />") case '-':
} result = number1 - number2;
document.write("Exiting switch block"); document.write(result)
</script> break;
</body>
case '*':
</html>
result = number1 * number2;
Output document.write(result)
Entering switch block break;
Good job case '/':
Exiting switch block result = number1 / number2;
document.write(result)
break;
case '%':
result = number1 % number2;
document.write(result)
break;
default:
document.write("Wrong Arithmetic Operator")
break;
}
</script>
</head>
<body>
</body>
</html>
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Loop in JavaScript
Example:
While writing a program, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce the
number of lines. <html>
<body>
1) 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. <script type = "text/javascript">
var count = 0;
Syntax:
document.write("Starting Loop ");
while (expression)
while (count < 10) {
{
document.write("Current Count : " + count + "<br />");
Statement(s) to be executed if expression is true
count++;
}
}
A while loop evaluates the condition inside the parenthesis (). document.write("Loop stopped!");
If the condition evaluates to true, the code inside the while loop is executed. </script>
The condition is evaluated again.
This process continues until the condition is false. <p>Set the variable to different value and then try...</p>
When the condition evaluates to false, the loop stops. </body>
</html>
Flow Chart
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...
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
2) The do...while Loop </script>
<p>Set the variable to different value and then try...</p>
The do...while loop is similar to the while loop except that the condition check happens at the
</body>
end of the loop. This means that the loop will always be executed at least once, even if the
</html>
condition is false.
Flow Chart
Output
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...
Note − Don’t miss the semicolon used at the end of the do...while loop.
Example:
Try the following example to learn how to implement a do-while loop in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Example break statement
The break statement is used to terminate from the loop immediately. When a break statement is
<html> encountered inside a loop, the loop iteration stops there, and control returns from the loop
<body> immediately to the first statement after the loop.
<script type = "text/javascript"> Example:
var count; <script type="text/javascript">
document.write("Starting Loop" + "<br />"); var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++)
for(count = 0; count < 10; count++)
{
{
document.write("Current Count : " + count );
if(count==5)
document.write("<br />");
{
}
break
document.write("Loop stopped!");
}
</script>
document.write("Current Count : " + count );
<p>Set the variable to different value and then try...</p>
</body> document.write("<br />");
</html> }
</script>
Output
Starting Loop Output:
Current Count : 0 Starting Loop
Current Count : 1 Current Count : 0
Current Count : 2 Current Count : 1
Current Count : 3 Current Count : 2
Current Count : 4
Current Count : 3
Current Count : 5
Current Count : 4
Current Count : 6
Current Count : 7
Current Count : 8 continue statement
Current Count : 9
The continue statement in Java is used to skip the current iteration of a loop.
Loop stopped!
Set the variable to different value and then try...
<script type="text/javascript">
var count;
document.write("Starting Loop" + "<br />");
}
</script>
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Output: 3. Floating number literals
Starting Loop A floating number has the following parts.
Current Count: 0 A decimal integer.
Current Count: 1 A decimal point ('.').
Current Count: 2 A fraction.
Current Count: 3 Example:
Current Count: 4 8.2935
Current Count: 6 -14.72
Current Count: 7
4. Boolean literals
Current Count: 8
The Boolean type has two literal values: true and false
Current Count: 9
5. Object literals
JavaScript Values or Literals: An object literal is zero or more pairs of comma-separated list of property names and
associated values, enclosed by a pair of curly braces.
In JavaScript an object literal is declared as follows:
1. Array literals
In Javascript, an array literal is a list of expressions, each of which represents an array element, 1. An object literal without properties:
enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it is var student = { }
initialized with the specified values as its elements, and its length is set to the number of
arguments specified. If no value is supplied it creates an empty array with zero length. 2. An object literal with a few properties :
var student =
Creating an empty array : {
var fruits = [ ]; First-name : "Akshay",
Creating an array with four elements. Last-name : "Rayy",
var fruits = ["Orange", "Apple", "Banana", "Mango"] Roll-No : 12
};
2. Integers literals
An integer must have at least one digit (0-9). Syntax Rules
No comma or blanks are allowed within an integer. There is a colon (:) between property name and value.
It does not contain any fractional part. A comma separates each property name/value from the next.
It can be either positive or negative if no sign precedes it is assumed to be positive. There will be no comma after the last property name/value pair.
In JavaScript, integers can be expressed in three different bases. 6. String literals
1. Decimal ( base 10) A string literal is zero or more characters, either enclosed in single quotation (') marks or
Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no double quotation (") marks.
leading zeros. You can also use + operator to join strings.
Example: 123 The following are the examples of string literals :
3. Octal (base 8)
Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number
is octal.
Example: 0123
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Array,Function and String
Main Event
Event is something that causes JavaScript to execute the code. JavaScript Array
JavaScript's interaction with HTML is handled through events that occur when the user or the An array is a special type of variable, which can store multiple values using special syntax.
browser manipulates a page. Every value is associated with numeric index starting with 0. The following figure illustrates
When the page loads, it is called an event. how an array stores values.
When the user clicks a button, that click to is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
Each available event has an event handler, which is a block of code (usually a JavaScript
function) that runs when the event fires.
Execution of appropriate code on occurrence of event is called event handling. JavaScript Array
Array Initialization
An array in JavaScript can be defined and initialized in two ways, array literal and Array
constructor.
a) Array Literal
Array literal syntax is simple. It takes a list of values separated by a comma and enclosed in
square brackets.
Syntax:
var array_name = [element0, element1, element2,... elementN];
The following example shows how to define and initialize an array using array literal
syntax.
Example:
var stringArray = ["one", "two", "three"];
var numericArray = [1, 2, 3, 4];
var mixedArray = [1, "two", "three", 4];
JavaScript array can store multiple element of different data types. It is not required to store
value of same data type in an array.
b) Array Constructor
You can initialize an array with Array constructor syntax using new keyword.
The Array constructor has following three forms.
Syntax:
Var arrayName = new Array ( Number length ); //creates new array with specified length
Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Var arrayName = new Array (element1, element2, element3, elementN); // creates new
array with elements specified in the bracket Looping the Array
Use for loop to access all the elements of an array using length property.
Example:
var mixed Array = new Array(1, "two", 3, "four"); Example: Access Array using for Loop
2) Array can be declared first and we can define the elements later. For this array make <script type=”text/javascript”>
use of index. var Arr = new Array("one", "two", "three", "four");
for (var i = 0; i < Arr.length ; i++)
Example {
document.write(Arr[i]);
var stringArray = new Array(); // Array Declaration }
stringArray[0] = "one"; //Array Initialization </script>
stringArray[1] = "two";
stringArray[2] = "three"; Adding an Array Element
stringArray[3] = "four"; 1. push() method
The JavaScript array push() method adds one or more elements to the end of the given array.
This method changes the length of the original array.
Array can only have numeric index (key). Index cannot be of string or any other data type.
Syntax
Accessing Array Elements The push() method is represented by the following syntax:
array.push(element1,element2 ... elementn)
An array elements (values) can be accessed using index (key). Specify an index in square bracket Let's see some examples of push() method
with array name to access the element at particular index. Index of an array starts from zero in
JavaScript. Example 1
<script>
Example: var arr=["AngularJS","Node.js"];
document.writeln("Length before invoking push(): "+arr.length+"<br>");
var stringArray = new Array("one", "two", "three", "four"); arr.push("JQuery","Bootstrap");
document.writeln("Length after invoking push(): "+arr.length+"<br>");
stringArray[0]; // returns "one" document.writeln("Update array: "+arr);
stringArray[1]; // returns "two" </script>
stringArray[2]; // returns "three"
stringArray[3]; // returns "four" Output:
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Example 1 Example:
Let's see a simple example to sort the array of string elements. The compare function compares all the values in the array, two values at a time (a, b).
<script type="text/javascript"> When comparing 40 and 100, the sort() method calls the compare function(40, 100).
var fruits=["Mango","Apple","WaterMelon","Pineapple"] The function calculates 40 - 100 (a - b), and since the result is negative (-60), the sort
var result=fruits.sort(); function will sort 40 as a value lower than 100.
document.write(result)
</script> Example
Output: Arrange the elements in ascending order using function.
Apple,Mango,Pineapple,WaterMelon <script>
var arr=[20,40,100,80,50];
var result=arr.sort(function (a,b)
{
Numeric Sort return a-b;
});
By default, the sort() function sorts values as strings. document.writeln(result);
This works well for strings ("Apple" comes before "Banana"). </script>
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than Output:
"1". 20,40,50,80,100
Because of this, the sort() method will produce incorrect result when sorting numbers.
<script type="text/javascript">
var arr=[100,25,200,30,45] Reversing an Array
var result=arr.sort(); The reverse() method reverses the elements in an array. You can use it to sort an array in
document.write(result) descending order:
</script> Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
Output: fruits.sort(); // First sort the elements of fruits
100,200,25,30,45 fruits.reverse(); // Then reverse the order of the elements
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Return :
Output:
A new array object that represents a joined array.
100,80,50,40,20
Example 1
Combining Array elements into a string: Here, we will print the combination of two arrays.
Array join() method
<script>
The JavaScript array join() method combines all the elements of an array into a string and var arr1=["C","C++","Python"];
return a new string. We can use any type of separators to separate given array elements. var arr2=["Java","JavaScript","Android"];
Syntax
var result=arr1.concat(arr2);
array.join(separator)
document.writeln(result);
Separator - It is optional. It represent the separator used between array elements. </script>
Returns a new string contains the array values with specified separator.
Output:
Example 1: C,C++,Python,Java,JavaScript,Android
<script type="text/javascript">
var fruits=["Mango","Apple","WaterMelon","Pineapple"] Example 2
var result=fruits.join(); Here, we will print the combination of three arrays.
document.write(result)
</script> <script>
Output: var arr1=["C","C++","Python"];
Mango,Apple,WaterMelon,Pineapple var arr2=["Java","JavaScript","Android"];
var arr3=["Ruby","Kotlin"];
Example 2 var result=arr1.concat(arr2,arr3);
In this example, we will separate the array elements using '-' separator. document.writeln(result);
<script type="text/javascript"> </script>
var fruits=["Mango","Apple","WaterMelon","Pineapple"] Output:
var result=fruits.join('-');
document.write(result) C,C++,Python,Java,JavaScript,Android,Ruby,Kotlin
</script>
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
It is used to fetch the part of the given string on the basis of the specified Syntax
substr() string.concat(str1,str2,...,strn)
starting position and length.
Parameter
It is used to fetch the part of the given string on the basis of the specified str1,str2,...,strn - It represent the strings to be combined.
substring()
index. Return
It is used to fetch the part of the given string. It allows us to assign positive Combination of strings.
slice() Example 1:
as well negative index.
<script>
toLowerCase() It converts the given string into lowercase letter. var x="Spc";
var y=".com";
toLocaleLowerCase It converts the given string into lowercase letter on the basis of host?s
var z=" Tutorials";
() current locale.
It splits a string into substring array, then returns that newly created
split()
array.
trim() It trims the white space from the left and right side of the string.
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Example 1
Retrieving character from given Position: <script>
var x="Javatpoint";
charAt() Method document.writeln(x.charCodeAt(3));
The JavaScript string charAt() method is used to find out a character present at the specified </script>
index in a string. Output:
The index number starts from 0 and goes to n-1, where n is the length of the string. 97
Syntax
String.charAt(index) Example 2
Parameter In this example, we will not pass any index number with the method. In such case, it will
index - It represent the position of a character. return the Unicode value of first character.
Returns <script>
A char value var x="Javatpoint";
Example 1 document.writeln(x.charCodeAt());//It will return Unicode value of 'J'
<script> </script>
var str="Javatpoint"; Output:
document.writeln(str.charAt(4)); 74
</script>
Output:
t Retrieving a Position of character in given String:
Example 2 1) indexOf() method
<script> The JavaScript string indexOf() method is used to search the position of a particular
var str="Javatpoint"; character or string in a sequence of given char values. This method is case-sensitive.
document.writeln(str.charAt()); //print first character The index position of first character in a string is always starts with zero. If an element is not
</script> present in a string, it returns -1.
Output:
J Syntax
indexOf(ch,index)
Findig a Unicode of a character: It start searching the element from the provided index value and then returns the index
position of specified char value.
charCodeAt() Method index - It is optional which represent the index position from where search starts.
A computer can understand only numbers and characters.
Unicode is a standard that assigns a number to every character, number and symbol. Example 1
The JavaScript string charCodeAt() method is used to find out the Unicode value of a Here, we will print the position of a single character.
character at the specific index in a string.
<script>
The index number starts from 0 and goes to n-1, where n is the length of the string. It returns var web="Learn JavaScript on Javatpoint";
NaN if the given index number is either a negative number or it is greater than or equal to the document.write(web.indexOf('a'));
length of the string. </script>
Syntax Output:
string.charCodeAt(index) 2
Parameter
index - It represent the position of a character.
Return
A Unicode value
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Example 2 Example:
In this example, we will provide the index value from where the search starts. <script>
var str="Javatpoint";
<script> document.writeln(str.substr(0,4));
var web="Learn JavaScript on Javatpoint"; </script>
document.write(web.indexOf('a',3));
</script> Output:
Output: Java
7
2) search() Method
The JavaScript string search() method is used to search the regular expression in the given 2) JavaScript String substring() Method
string. This method returns -1, if match is not found. The JavaScript string substring() method fetch the string on the basis of provided index and
returns the new sub string. It works similar to the slice() method with a difference that it
Syntax doesn't accepts negative indexes. This method doesn't make any change in the original string.
string.search(regexp)
Parameter Syntax
regexp - It represents the regular expression which is to be searched. string.substring(start,end)
Return Parameter
The position of searched character. start - It represents the position of the string from where the fetching starts.
end - It is optional. It represents the position up to which the string fetches.
Example: Return: Part of the string.
<script> Example
var str="JavaScript is a scripting language. Scripting languages are often interpreted"; <script>
document.writeln(str.search("scripting")); var str="Javatpoint";
</script> document.writeln(str.substring(0,4));
Output: </script>
16 Output:
Java
Syntax
Syntax
string.slice(start,end)
string.substr(start,length)
Parameter
Parameter
start - It represents the position of the string from where the fetching starts.
start - It represents the position of the string from where the fetching starts.
end - It is optional. It represents the position up to which the string fetches.
length - It is optional. It represents the number of characters to fetch.
Return
Return: Part of the string.
Part of the string
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
Example 1 Example
Here, we will print the part of the string by passing starting and ending index. In the following example, various cases of strings such as only strings, strings with
numbers, etc have been taken and sent through the parseInt() function. Later on, their
<script>
integer values, if present, have displayed as shown in the output.
var str = "SpcAcademy";
document.writeln(str.slice(2,5));
</script> <!DOCTYPE html>
<html>
Output: <head>
row <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
Example 2 <title></title>
Here, we will provide starting index only. In such case, the method fetches the string up to its
<script>
length.
var a = "10";
<script> document.write("value is " + parseInt(a)+"<br>");
var str = "SpcAcademy"; var b = "420-23-567";
document.writeln(str.slice(4)); document.write('value is ' + parseInt(b)+"<br>");
</script> var c = "string";
Output: document.write("value is " + parseInt(c)+"<br>");
wAcademy var d = "2String"
document.write("value is " + parseInt(d)+"<br>");
Example 3
</script>
In this example, we will provide negative number as an index. In such case, the method starts
fetching from the end of the string.
</head>
<script> <body>
var str = "SpcAcademy"; </body>
document.writeln(str.slice(-5)); </html>
</script>
Output
Output: value is 10
ademy value is 420
value is NaN
Convert a string into integer value is 2
To convert a string to an integer parseInt() function is used in javascript. parseInt() function
returns NaN( not a number) when the string doesn’t contain number.
If a string with a number is sent then only that number will be returned as the output.
This function won't accept spaces.
If any particular number with spaces is sent then the part of the number that presents before
space will be returned as the output.
syntax
parseInt(value);
This function takes a string and converts it into an integer. If there is no integer present in the
string, NaN will be the output.
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String
If the separator is present at the beginning or the end of the string, then it still has the effect of
2) toUpperCase() Method splitting. The returned array consists of an empty string of zero length that appears at the
beginning or the last position of the returned array.
The JavaScript string toUpperCase() method is used to convert the string into uppercase letter.
This method doesn't make any change in the original string.
limit: It is also an optional parameter. It is a non-negative integer that specifies the number of
limits. It defines the higher limit on the number of splits to be found in the given string. If it is
Syntax
given, it splits the string at each occurrence of the specified separator. It stops when the limit
string.toUpperCase()
entries have been placed in the array.
Return
String in uppercase letter.
An array can contain fewer entries than the given limit. It happens when the end of the string
Example
is reached before the limit is reached.
<script>
var str = "javatpoint";
Let's understand the split() method using some examples.
document.writeln(str.toUpperCase());
</script>
Example1
Output:
In this example, the split() function splits the string str wherever the whitespace (" ") occurs and
JAVATPOINT
returns an array of strings. Here, we are using the limit argument and providing the value of the
limit argument to 3.
<script>
var str = 'Welcome to the Spc Computer Academy'
var arr = str.split(" ", 3);
document.write(arr);
</script>
Output
Welcome,to,the
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String
<body>
<form name="Myform" action="" method="get">
Enter Something in Textbox
<input type="text" name="ID">
<input type="button" name="button" value="Back" onclick="fun()">
</form>
</body>
</html>
Output:
Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
form name="myform"
Notes on GET:
Defines and names the form. Elsewhere in the JavaScript you can reference this form by Appends the form data to the URL, in name/value pairs
the name myform. NEVER use GET to send sensitive data! (the submitted form data is visible in the URL!)
The length of a URL is limited (2048 characters)
action="" GET is good for non-secure data, like query strings in Google
The action tag defines the action that the browser will take to tackle the form when it is
Notes on POST:
submitted. Here, we have taken no action. Appends the form data inside the body of the HTTP request (the submitted form data is
The action attribute specifies a URL that will process the form submission.
not shown in the URL)
As this example is not designed to submit anything, the URL for the CGI program is
POST has no size limitations, and can be used to send large amounts of data.
omitted.
Form submissions with POST cannot be bookmarked.
method="get"
4. onsubmit
It defines the method data is passed to the server when the form is submitted.
The purpose of the HTML onsubmit attribute is to execute the code specified, when the
associated form is submitted. HTML onsubmit attribute supports form element. There is no
input type="text" defines the text box object. This is standard HTML markup.
default value of HTML onsubmit attribute.
Syntax
input type="button" defines the button object. This is standard HTML markup except for
<form onsubmit="value" > .... </form>
the onClick handler.
Example:
<form name="myform" action="" method="get" onsubmit="alert('Form is submitted')">
onclick="fun( )" is an event handler -- it handles an event, in this case clicking thebutton.
When the button is clicked, JavaScript executes the expression within the quotes. It calls
function fun(). <head>
<title>Switch</title>
<script type="text/javascript">
HTML Form Attributes
function fun()
1. Name:
The name attribute specifies the name of a form. The name attribute is used to reference {
elements in a JavaScript, or to reference form data after a form is submitted. alert("Hello, Your form is submitted")
Syntax
<form name="text"> }
</script>
2. The Action Attribute
The action attribute defines the action to be performed when the form is submitted. </head>
Usually, the form data is sent to a file on the server when the user clicks on the submit button. <body>
<form name="Myform" action="" method="get" onsubmit="fun()">
Tip: If the action attribute is omitted, the action is set to the current page.
Enter Something in Textbox
3. The Method Attribute
<input type="text" name="ID">
The method attribute specifies the HTTP method to be used when submitting the form data.
The form-data can be sent as URL variables (with method="get") or as HTTP post transaction <input type="submit" name="button" value="Submit">
(with method="post"). </form>
The default HTTP method when submitting form data is GET.
Example </body>
<form action="/action_page.php" method="get">
Example
<form action="/action_page.php" method="post">
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
Output:
After clicking on submit button, this will submit the form to server and will redirect the page
to action value.
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
Output:
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
</head>
<body>
<form>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="pwd" minlength="6" maxlength="8"><br><br>
<input type="submit" value="SignIn" >
</form>
</body>
</html>
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
<label>Select Year</label>
<select name="Year" id="S1">
<option value="FY">FY</option>
<option value="SY">SY</option>
<option value="TY">TY</option>
</select><br><br>
<label>Address</label><br>
<textarea name="Address" rows="5" cols="20"></textarea><br><br>
<label for="E1">Eamil ID</label><br>
<input type="email" name="Email Id" id="E1"><br><br>
<label for="P1">Password</label><br>
<input type="Password" name="Password"><br><br>
<input type="Submit" name="Register" value="Register" onsubmit="alert('Form submitted
Successfully')">
<input type="reset" name="Resset" value="Reset" onclick="alert('Form Reset')">
</form>
</body>
</html>
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
getElementById ( ) Method
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, 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. However, if more than one element with the specified ID
exists, the getElementById() method returns the first element in the source code.
Syntax
getElementById(T1)
Example 1:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to change the color of button.</p>
<input type="button" id="b1" value="click" onclick="myFunction()">
<script>
function myFunction()
{
document.getElementById("b1").style.background = "red";
}
</script>
</body>
</html>
Output:
innerHTML property
Each HTML element has an innerHTML property that defines both the HTML code and the text
that occurs between that element’s opening and closing tag.
By changing element’s innerHTML after some user interaction, we can make much more
interactive pages.
For this, we must give some id to the element and then place that id in getElementById
function.
Example :
<!DOCTYPE html>
<html>
<body>
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
<form>
<p id="demo">Click the button to change the text in this paragraph.</p> 1. onfocus
<input type="button" name="Try it" onclick="myFunction()" value="Try it">
</form> The onfocus event occurs when an element gets focus.
<script>
<!DOCTYPE html>
function myFunction()
<html>
{
<head>
document.getElementById("demo").innerHTML = "Hello World"; <title></title>
} </head>
</script> <body>
</body> <script type="text/javascript">
</html> function myFunction()
{
Example 2:
<!DOCTYPE html>
<html>
FORM EVENTS <body>
Event is something that causes JavaScript to execute the code. <p>When the input field gets focus, a function is triggered which changes the background-
JavaScript's interaction with HTML is handled through events that occur when the user or the color.</p>
browser manipulates a page. Enter your name:
When the page loads, it is called an event. <input id="t1" type="text" onfocus="myFunction()">
When the user clicks a button, that click too is an event. <script>
function myFunction()
Other examples include events like pressing any key, closing a window, resizing a window, etc.
{
document.getElementById("t1").style.background = "yellow";
Event Handler:
}
Each available event has an event handler, which is a block of code (usually a JavaScript </script>
function) that runs when the event fires. </body>
Execution of appropriate code on occurrence of event is called event handling. </html>
Output:
Form Events:
1. onfocus
2. onchange
3. onblur
4. onselect
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
onselect onchange
Execute a JavaScript after some text has been selected in an <input> element:
Supported HTML tags: <input type="file">, <input type="password">, <input Example 1:
type="text">, and <textarea> <!DOCTYPE html>
<html>
Example: <body>
<!DOCTYPE html>
<html> <p>Modify the text in the input field, then click outside the field to fire the onchange event.
<body> </p>
Example 2:
<!DOCTYPE html>
<html>
<body>
<p>This example demonstrates how to assign an "onchange" event to an input element.</p>
Enter your name:
<input type="text" id="fname" onchange="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");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
Output: </script>
</body>
</html>
Output:
onblur
The onblur event occurs when an object loses focus.
The onblur event is the opposite of the onfocus event.
<!DOCTYPE html>
<html>
<body>
<p>Write something in the input field, and then click outside the field to lose focus (blur).</p>
<input type="text" id="fname" onblur="myFunction()" > Example2: mouseover and mouseout events
<script>
function myFunction() <!DOCTYPE html>
{ <html>
alert("Input field lost focus."); <body>
} <p>This example demonstrates how to assign red color when the mouse is over Register
</script> button and assign Green color when the mouse is moved out from Register button </p>
</body>
</html> <input type="button" id="b1" value ="register" onmouseover="mouseOver()"
onmouseout="mouseOut()">
mouseover and mouseout events <script>
function mouseOver()
Example1: mouseover and mouseout events
{
document.getElementById("b1").style.color = "Red";
<html>
}
<head>
function mouseOut()
<h1> Javascript Events </h1>
{
<h2 onmouseover="mouseoverevent()" onmouseout="onmouseoutevent()"> Keep cursor over
document.getElementById("b1").style.color = "Green";
me</h2>
}
</script>
</head>
</body>
<body>
</html>
<script language="Javascript" type="text/Javascript">
Output
function mouseoverevent()
{
alert("Welcome to Spc");
}
function onmouseoutevent()
{
alert("Welcome Spc World");
}
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
<!DOCTYPE html>
<html>
<body>
<script>
function mouseDown()
{
document.getElementById("myP").style.color = "red"; Key Events
}
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
</body>
onkeypress </html>
This event occurs when the user presses a key that produces a character value. These include Output:
keys such as the alphabetic, numeric, and punctuation keys. Modifier keys such as ‘Shift’,
‘CapsLock’, ‘Ctrl’ etc. do not produce a character, therefore they have no ‘keypress’ event
attached to them.
<!DOCTYPE html>
<html>
<body>
<p>A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" onkeypress="myFunction()">
<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>
</body>
</html>
Output:
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
Example 1
<html>
<head>
<p>Change option List according to User Selection </p>
<script language ="javascript" type="text/javascript">
function DisplayList(ElementValue)
{
with (document.forms.frm1) Q] Write a HTML script which displays 2 radio buttons to the users for fruits and
{ vegetables and 1 option list. When user select fruits radio button option list should
if (ElementValue == 1) present only fruits names to the user & when user select vegetable radio button option
{ list should present only vegetable names to the user
op1[0].text = "WPD"
op1[0].value = 1 <html>
op1[1].text = "PIC" <head>
op1[1].value = 2
op1[2].text = "Maths" <title>HTML Form</title>
op1[2].value = 3
<script language="javascript" type="text/javascript">
}
if (ElementValue == 2) function updateList(ElementValue)
{
{
op1[0].text = "OOP"
op1[0].value = 1 with(document.forms.myform)
op1[1].text = "DSU"
{
op1[1].value = 2
op1[2].text = "DBMS" if(ElementValue == 1)
op1[2].value = 3
} {
} optionList[0].text="Mango";
}
</script> optionList[0].value=1;
</head> optionList[1].text="Banana";
<body>
<form name="frm1"> optionList[1].value=2;
<select name="op1" size="3"> optionList[2].text="Apple";
<option Value=1> WPD
<option Value=2>PIC optionList[2].value=3;
<option Value=3>Maths }
</select>
<br> if(ElementValue == 2)
<input type="radio" name="subjects" checked="true" value=1 onclick = {
"DisplayList(this.value)"> First Year
<input type="radio" name="subjects" value=2 onclick="DisplayList(this.value)">Second Year optionList[0].text="Potato";
<br> optionList[0].value=1;
<input name="Submit" value="Submit" type="submit">
</form> optionList[1].text="Cabbage";
</body>
optionList[1].value=2;
<html>
optionList[2].text="Onion";
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
optionList[2].value=3;
} Evaluating Checkbox Selection
} <html>
<head>
}
<title>Evaluating Checkboxes</title>
</script> <h3>Select the subjects</h3>
<script language="Javascript" type="text/javascript">
</head> function show()
<body> {
var x='You Selected '
<form name="myform" action="" method="post"> with (document.forms.frm1)
<p> {
if (a.checked == true)
<select name="optionList"> {
<option value="1">Mango</option> x+=a.value + " "
}
<option value="2">Banana</option> if (b.checked == true)
<option value="3">Apple</option> {
x+=b.value + " "
</select> }
<br><br> if (c.checked == true)
{
<input type="radio" name="grp1" value=1 checked="true" x+=c.value + " "
}
onclick="updateList(this.value)">Fruits
if (d.checked == true)
<input type="radio" name="grp1" value=2 {
x+=d.value + " "
onclick="updateList(this.value)">Vegetables
}
<br> if (e.checked == true)
{
<input name="Submit" value="Submit" type="submit">
x+=e.value + " "
</p> }
}
</form>
document.write(x)
</body> }
</script>
</html> </head>
<body>
<form name="frm1" action="" method="post">
<P>
<input type="checkbox" name="a" value="PIC">C
<br>
<input type="checkbox" name="b" value="C++">C++
<br>
<input type="checkbox" name="c" value="java">JAVA
<br>
<input type="checkbox" name="d" value="php">PHP
<br>
<input type="checkbox" name="e" value="jscript">JAVASCRIPT
<br><br>
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling
Output
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Cookies and Browser Data
Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data
How Cookies Works? Example Write a JavaScript for creating a cookie for the user name.
o When a user sends a request to the server, then each of that request is treated as a new request
sent by the different user. <html>
o So, to recognize the old user, we need to add the cookie with the response from the server to <head>
browser at the client-side.
o Now, whenever a user sends a request to the server, the cookie is added with that request <script type = "text/javascript">
automatically. Due to the cookie, the server recognizes the users. function WriteCookie()
{
if( document.myform.customer.value == "" )
{
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
Cookies remembers the information about the user in the following ways -
document.write ("Setting Cookies : " + "name=" + cookievalue );
Step 1: When the user visits the web page his/her name can be stored in a cookie
}
Step 2: Next time when the user visits the page, the cookie remembers his/her name.
</script>
</head>
There are two types of cookies: Session cookies and persistent cookies
<body>
Session Cookies : Session cookies is a cookie that remains in temporary memory only
<form name = "myform" action = "">
while user is reading and navigating the web site. The cookie is automatically deleted
Enter name: <input type = "text" name = "customer"/>
when the user exits the browser application.
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()">
</form>
Persistent Cookies : A persistent cookie is a cookie that is assigned an expiration date. A
</body>
persistent cookie is written to the computer's hard disk and remains there until the
</html>
expiration date has been reached; then it is deleted.
Now your machine has a cookie called name. You can set multiple cookies using multiple key =
Creating Cookies value pairs separated by comma.
JavaScript can create, read or delete a cookie using document.cookie property
The simplest way to create a cookie is to assign a string value to the document.cookie object, Reading a Cookie Value
which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date"; It is a common practice to create a cookie and then read the value of the created cookie.
The document.cookie string will keep a list of NAME=VALUE pairs separated by semicolons, name
document.cookie = "username=Spc"; is the name of a cookie and value is its string value.
Using the split() function the string of cookies is break into key and values.
Here the expires attribute is optional. The split() method finds the = character in the cookie, and then take all the characters to the left of
If you provide this attribute with a valid date or time, then the cookie will expire on a given date the= and store them into array [0].
or time and thereafter, the cookies' value will not be accessible. Next the split() method takes all the characters from the right of the = up to semicolon ( ; ) but not
Including the semicolon, and assign those characters to array[1]
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may Thus we can obtain the name value pair in array[0] and array[1] respectively.
want to use the JavaScript escape() function to encode the value before storing it in the cookie. If
you do this, you will also have to use the corresponding unescape() function when you read the Following example illustrates how to read the cookies value.
cookie value.
Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data
function WriteCookie() {
// Now take key value pair out of this array var now = new Date();
for(var i=0; i<cookiearray.length; i++) now.setMonth( now.getMonth() + 1 );
{ cookievalue = escape(document.myform.customer.value) + ";"
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1]; document.cookie = "name=" + cookievalue;
document.write ("Key is : " + name + " and Value is : " + value); document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
} }
}
//--> </script>
</script> </head>
</head>
<body>
<form name = "myform" action = "">
<body>
Enter name: <input type = "text" name = "customer"/>
<form name = "myform" action = ""> <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
<p> click the following button and see the result:</p> </form>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/> </body>
</form> </html>
</body>
</html>
Note − There may be some other cookies already set on your machine. The above code will display
all the cookies set on your machine.
Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data
Deleting a Cookie It is possible to open a new browser window from a currently running JavaScript .
For that purpose the window object is used.
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return This window object has various useful properties and methods.
nothing. To do this, you just need to set the expiry date to a time in the past. The window.open() method is used to open a new browser window or a new tab depending on
Example the browser setting and the parameter values.
Try the following example. It illustrates how to delete a cookie by setting its expiry date to one
Syntax
month behind the current date.
Window.open(URL,name,style)
<html>
<head>
<script type = "text/javascript">
function WriteCookie() {
var now = new Date(); URL Optional. Specifies the URL of the page to open. If no URL is specified, a new
now.setMonth( now.getMonth() - 1 ); window/tab with about:blank is opened
cookievalue = escape(document.myform.customer.value) + ";"
name Optional. Specifies the target attribute or the name of the window. The following values
document.cookie = "name=" + cookievalue; are supported:
document.cookie = "expires=" + now.toUTCString() + ";"
_blank - URL is loaded into a new window, or tab. This is default
document.write("Setting Cookies : " + "name=" + cookievalue );
_parent - URL is loaded into the parent frame
}
</script> _self - URL replaces the current page
</head>
style Optional. A comma-separated list of items, no whitespaces. The following values are
<body> supported:
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/> fullscreen=yes|no|1|0 Whether or not to display the browser in full-
</form> screen mode. Default is no.
</body>
</html> height=pixels The height of the window. Min. value is 100
4.2 Browser top=pixels The top position of the window. Negative values
not allowed
Opening a Window
Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data
width=pixels The width of the window. Min. value is 100 Example 3: Open Specified URL
<!DOCTYPE html>
<html>
Example 1: Open an about:blank page in a new window/tab
<body>
<p>Click the button to open a new browser window.</p>
<!DOCTYPE html>
<button onclick="myFunction()">Try it</button>
<html>
<script>
<body>
function myFunction() {
window.open("https://spccomputeracademy.business.site/");
<p>Click the button to open an about:blank page in a new browser window that is 200px
}
wide and 100px tall.</p>
</script>
Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data
<!DOCTYPE html>
<html>
<body>
Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data
<br><br><br><br><br><br><br><br>
<button onclick="setTimeout(myFunction, 2000)">Click Me</button>
<p><strong>Note:</strong> Alert popup will be displayed 2 seconds after clicking the <P> ------------ Window Scrolled</p>
button.</p> </body>
</body> </html>
</html>
scrollTo() 1. window.location.pathname :
Gives complete path at which the web page is located.
<html> 2. window.location.hostname:
<head> Gives name of host on which the webpage is running. It gives domain name
3. window.location.protocol:
<script type = "text/javascript"> Gives the protocol used for the webpage. Such as HTTP, HTTPS
function scrollwindow()
{ Q Write a JavaScript code to get a pathname.
window.scrollTo(0,200);
} <html>
<head>
</script> <script type="text/javascript">
function display()
</head> {
<body> document.getElementById("ID").innerHTML = "This web page is at path:" +
window.location.pathname;
<p>click to scroll</p> }
<input type="button" value="Scroll Window" onclick="scrollwindow()"> </script>
<p>A</p> </head>
<body>
<br><br><br><br><br><br> <input type="button" value="GetPath" onclick="display()">
<p id="ID"></p>
<p>B</p>
<br><br><br><br><br><br>
<p>C</p>
<br><br><br><br><br><br>
<p>D</p>
<br><br><br><br><br><br>
<p>E</p>
Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data
</body> {
</html> window.history.back();
}
Q Write a JavaScript code to get the protocol. function next()
<html> {
<head> window.history.forward();
<script type="text/javascript"> }
function display() </script>
{ </head>
document.getElementById("ID").innerHTML = "The protocol of Web Page is:" + <body>
window.location.protocol;
} <input type="button" value="Previous" onclick="previous()">
</script> <input type="button" value="Next" onclick="next()">
</head>
<body> </body>
<p>Click the button to get the Protocol</p> </html>
<input type="button" value="GetProtocol" onclick="display()">
<p id="ID"></p>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function display()
{
document.getElementById("ID").innerHTML = "The hostname of Web Page is:" +
window.location.hostname;
}
</script>
</head>
<body>
<input type="button" value="GetHost" onclick="display()">
<p id="ID"></p>
</body>
</html>
History
<html>
<head>
<script type="text/javascript">
function previous()
Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames
Regular Expressions, Rollover and Frames Q] Write a program to check whether the string contains the given pattern or not.
<!DOCTYPE html>
JavaScript Regular Expressions <html>
A regular expression is a sequence of characters that forms a search pattern.
The search pattern can be used for text search and text replace operations. </head>
What Is a Regular Expression? <script type="text/javascript">
A regular expression is a sequence of characters that forms a search pattern. var p=/spc computer academy/i
When you search for data in a text, you can use this search pattern to describe what you are function testMatch()
searching for. {
A regular expression can be a single character, or a more complicated pattern. var str = T1.value;
Regular expressions can be used to perform all types of text search and text replace operations.
if(p.test(str))
Syntax {
/pattern/modifiers; alert("String " + str + " contains the given pattern")
}
Example else
var patt = /spc/i; {
Example explained:
alert("String " + str + " does not contains the given pattern")
/spc/i is a regular expression
spc is a pattern (to be used in a search). }
i is a modifier (modifies the search to be case-insensitive). }
</script>
</head>
Modifiers <body>
Modifiers are used to perform case-insensitive and global searches:
Modifier Description Enter string <input type="text" id="T1">
<button onclick="testMatch()">Try it</button>
g Perform a global match (find all matches rather than stopping after the first match) </body>
i Perform case-insensitive matching </html>
test()
The test() method tests for a match in a string.
This method returns true if it finds a match, otherwise it returns false.
Syntax
RegExpObject.test(string)
Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames
Brackets Quantifiers
Brackets ([]) have a special meaning when used in the context of regular expressions. They are The frequency or position of bracketed character sequences and single characters can be denoted
used to find a range of characters. by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all
follow a character sequence.
Sr.No. Expression & Description
3 [0-9] 3 p?
It matches any decimal digit from 0 through 9. It matches any string containing at most one p.
4 [^0-9] 4 p{N}
Find any character NOT between the brackets (any non- It matches any string containing a sequence of N p's
digit)
5 p{2,3}
4 [a-z] It matches any string containing a sequence of two or three p's.
It matches any character from lowercase a through
lowercase z. 6 p{2, }
It matches any string containing a sequence of at least two p's.
5 [A-Z]
It matches any character from uppercase A through 7 p$
uppercase Z. It matches any string with p at the end of it.
6 [a-Z] 8 ^p
It matches any character from lowercase a through It matches any string with p at the beginning of it.
uppercase Z.
7 (x|y)
Find any of the alternatives specified
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging
from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.
Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames
\W Find a non-word character Tests for a match in a string. It returns the index of the match, or -1 if the search
search()
fails.
\d Find a digit
Executes a search for a match in a string, and replaces the matched substring with a
replace()
\D Find a non-digit character replacement substring
\s Find a whitespace character Uses a regular expression or a fixed string to break a string into an array of
split()
substrings.
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word, beginning like this: \bHI, end like
this: HI\b Matching Words
\B Find a match, but not at the beginning/end of a word The match() function is used to match a word in given string.
<!DOCTYPE html>
\0 Find a NULL character <html>
\0 returns the position where the NUL character was found. If no match is <body>
found, it returns -1.
<p>Enter some value in textbox and click on button to find characters NOT inside the
brackets.</p>
\n Find a new line character
\n returns the position where the newline character was found. If no match is
found, it returns -1.
<script>
\f Find a form feed character function myFunction() {
var patt1 = /student/gi;
\r Find a carriage return character var str = T1.value;
var result = str.match(patt1);
\t Find a tab character if(result!=null)
{
\v Find a vertical tab character alert(" Entered string contains word student");
\xxx Find the character specified by an octal number xxx
}
else
{
\xdd Find the character specified by a hexadecimal number dd
alert(" Entered string does not contain word student");
\udddd Find the Unicode character specified by a hexadecimal number dddd }
}
</script>
Enter string <input type="text" id="T1">
<button onclick="myFunction()">Try it</button>
</body>
</html>
Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames
<!DOCTYPE html>
<html> Matching Digits and Non Digits
<body>
The string may contain digits and non-digits i.e. characters other than digits.
<p>Enter some value in textbox and click on button to find characters NOT inside the Determining whether the string contains digits or non digits is a common task in any search
brackets.</p> pattern. Validating telephone number is one of the task where it requires Matching Digits.
This can be simplified by JavaScript by writing the regular expression.
If we want to search digits, then we use \d and if we want to search non-digits, then we use \D
<script>
function myFunction() { Example1 : To check whether string contains digits or not
var patt1 = /[^ht]/gi;
var str = T1.value; <!DOCTYPE html>
var result = str.match(patt1); <html>
alert("Non Matching characters are "+ result); </head>
} <script type="text/javascript">
</script> var p=/\d/i
Enter string <input type="text" id="T1"> function testMatch()
<button onclick="myFunction()">Try it</button> {
var str = T1.value;
</body> if(p.test(str))
</html> {
alert("String " + str + " contains the digits")
}
Entering Range of Characters: else
{
For matching any digit we need not have to enter every digit right from 0 to 9. alert("String " + str + " does not contains digits")
Similarly for matching letters we need not have to test with every single alphabet. We can achieve this by }
entering range of Characters. }
</script>
For example - to match a characters from ‘a’ to ‘d’ we must have a regular expression as [a-d]. Thus placing </head>
the range within a square bracket helps us to evaluate a complete range of set of characters. <body>
Enter string <input type="text" id="T1">
<!DOCTYPE html> <button onclick="testMatch()">Try it</button>
<html> </body>
<body> </html>
<p>Enter some value in textbox and click on button to find characters within the range.</p>
<script>
function myFunction() {
var patt1 = /[a-d]/gi;
var str = T1.value;
var result = str.match(patt1);
alert("characters within the range are "+ result);
}
</script>
Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames
<!DOCTYPE html>
<html>
</head>
<script type="text/javascript">
var p=/\W/i
function testMatch()
{
var str = T1.value;
if(p.test(str))
{
alert("String " + str + " contains the special character")
}
else
{
alert("String " + str + " does not contain special character")
Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames
Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames
marginwidth Example 2:
4 This attribute allows you to specify the width of the space between the left and
right of the frame's borders and the frame's content. The value is given in pixels. </html>
For example marginwidth = "10".
<!DOCTYPE html>
marginheight <html>
5 This attribute allows you to specify the height of the space between the top and
bottom of the frame's borders and its contents. The value is given in pixels. For <head>
example marginheight = "10". <title>HTML Target Frames</title>
</head>
noresize
By default, you can resize any frame by clicking and dragging on the borders of a <frameset cols = "200, *">
6 <frame name = "left" src = "pr4.html" />
frame. The noresize attribute prevents a user from being able to resize the frame. For
example noresize = "noresize". <frame name = "center" src = "pr4.html" />
scrolling <noframes>
This attribute controls the appearance of the scrollbars that appear on the frame. <body>Your browser does not support frames.</body>
7 </noframes>
This takes values either "yes", "no" or "auto". For example scrolling = "no" means it
should not have scroll bars. </frameset>
</html>
Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames
Text Rollover
Text rollover is a technique in which whenever user rollover the text, JavaScript allows to change the page <a onmouseover="display1()">
element usually some graphics image. <br>
Carefully placed rollovers can enhance a visitors experience when browsing the web page. <b><u>mango</u></b>
<html> </a>
<body> <br>
<a> <a onmouseover="display2()">
<img src ="mango.jpeg" name="fruit" width="650px" height="550px"> <br>
</a> <b><u>Pineapple</u></b>
<a onmouseover="document.fruit.src='mango.jpeg'"> </a>
<br> <br><br><br>
<b><u>Mango</u></b> <a>
</a> <img src ="mango.jpeg" name="fruit" width="650px" height="550px">
<br><br><br> </a>
<p id="para">Trees of mango are larger than Pineapple </p>
<a onmouseover="document.fruit.src='banana.jpeg'">
<b><u>banana</u></b> </body>
</a> </html>
<br><br><br>
<a onmouseover="document.fruit.src='pineapple.jpeg'">
<b><u>pineapple</u></b>
</a>
<br><br/><br/>
</body>
</html>
Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)