JavaScript Lab Manual
JavaScript are written inside <script> tag in an HTML Page.
JavaScript Variables
Variables are containers for storing data. To declare JavaScript variable use ‘var’.
Syntax: var variable_name [= expression];
e.g. var year = 7;
Type of a variable is dynamic - This means that the same variable can be used to hold different data types.
It depends on the type of data it contains. So we need not to specify datatype for a variable.
JavaScript Outputs
JavaScript can display data in different ways.
Writing into an HTML element, using innerHTML (we will discuss later)
Writing into the HTML output using [Link]().
Writing into an alert box, using [Link]().
Writing into the browser console, using [Link](). – is used for debugging error.
[Link]() – is used to display data to an HTML page in the browser. It can also write/display
HTML tags.
e.g. [Link](“Hello Everyone!”);
[Link](“<h2> This is Heading 2 </h2>”);
Note: [Link]() is used for test only. If we use it dynamically or after an HTML page is loaded, it
will override previous contents of HTML.
[Link]() – is an alert box. It displays data in the alert box.
Conditional Statements
Conditional statements are used to perform different actions based on different conditions. we have four
conditional statements:
If
If else
If else if
Switch
If Statement
If statement is used to specify a block of JavaScript code to be executed if a condition is true.
Syntax: if (condition) {
// block of code to be executed if the condition is true
}
e.g var test = 9;
if ( test > 9) {
[Link](“Very Good!”);
}
If-else Statement
If else statement is used to specify a block of JavaScript code to be executed if a condition is both true
and false.
Syntax: if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
e.g var test = 7;
if ( test > 9 ) {
[Link](“Very Good!”);
}
else {
[Link](“ Good !”);
}
If else if Statement
If else statement is used to specify a new condition if the first condition is false.
Syntax: if (condition1) {
// block of code to be executed if the condition is true
} else if (condition2){
// block of code to be executed if the condition1 is false
}else {
// block of code to be executed if the condition1 & condition2 is false
}
e.g var test = 7;
if ( test > 9 ) {
[Link] (“Very Good!”);
}
else if (test >7) {
[Link] (“Good!”);
}
else if (test > 5) {
[Link] (“Satisfactory!”);
}
else {
[Link] (“Failed!”);
}
Switch statement
The switch statement is used to perform different actions based on different conditions. It is used to select
one of many code blocks to be executed.
Syntax : switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
e.g . var Number = 8;
switch ( test) {
case 10:
case 9:
[Link](“Very Good!”);
break;
case 8:
case 7:
[Link](“Good!”);
break;
case 6:
case 5:
[Link](“Satisfactory!”);
break;
default :
[Link](“Failed”);
}
The Example displays
- “Very Good!” if test =10 or test = 9,
- “Good!” if test = 8 or test = 7
- “Satisfactory” if test = 6 or test = 5
- “Failed” if the test is other than the above Numbers.
Iterative Statements/Loops
Iterative statements/Loops can execute a block of code a number of times. we have three loops : for,
While ,do/while.
For Loop
- Loops through a block of code a number of times.
Syntax: for (statement 1; statement 2; statement 3) {
// code block to be executed}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed
e.g. for( var i=0; i<10; i++){
[Link](i+“<br>”);
}
The Example displays a list of Number from 0 to 9 vertically.
While Loop
Loops through a block of code while a specified condition is true
Syntax : while (condition) {
// code block to be executed }
e.g. var Number = 0;
while(Number < 10) {
[Link](Number + “<br>”);
Number ++;
}
The Example displays a list of Numbers from 0 to 9 vertically.
Do/while Loop
This loop will execute the code block once, before checking if the condition is true, and then it will repeat
the loop as long as the condition is true.
Syntax : do {
// code block to be executed
}
while (condition);
e.g.1. var Number = 0;
do {
[Link](Number + “<br>”);
Number ++; }
while(Number < 10);
The Example displays a list of Numbers from 0 to 9 vertically.
e.g. 2. var Number = 12;
do {
[Link](Number + “<br>”);
Number ++; }
while(Number < 10);
The Example displays Number 12. Since the first block code inside do is executed without checking the
condition, number 12 can be displayed even though it doesn’t meet the requirement/condition.
Function
A JavaScript function is a block of code designed to perform a particular task. A function is executed
when "something" invokes it (calls it).
Syntax: function functionName (parameter1, parameter2, parameter3) {
// code to be executed
}
e.g. function add( x,y){ // function add is defined here
return x+y;
}
var a = 5;
var b= 7;
[Link](“The result is “+add(a,b) ); //add function is called. The parameters are a and b.
The result of the example is: The sum of 5 + 7 = 12
Array
An array is a special variable, which can hold more than one value at a time. Arrays are used to store
multiple values in a single variable.
Syntax: var array_name = [item1, item2, ...]; OR
var array_name = new Array( item1, item2, …);
An array element can be accessed by referring to the index number.
The length property of an array returns the length of an array (the number of array elements).
e.g. var odds = [1,3,5,7,9];
var leng = [Link]; // the length of odds is 5
for(var i=0; i<leng ; i++) {
[Link](odds[i]+ “<br>”);
}
Objects
Objects are like real world objects that have properties and methods. JavaScript objects are containers
for named values called properties or methods.
Example: var person = {firstName:“Abebe", lastName:“Alemu", age:30, eyeColor:“brown"
fullName: function( ){ return [Link] +” “ + [Link]; }
}; OR
Example: var person = new Object();
[Link] = “Abebe";
[Link] = “Alemu";
[Link] = 30;
[Link] = "brown";
[Link]() {
return [Link] +” “ + [Link];
};
Events
An HTML event can be something the browser does, or something a user does. HTML allows event
handler attributes, with JavaScript code, to be added to HTML elements.
Example: 1. <button = Date()">The time
is?</button>
2. <input type=”text” name=”firstName” > <script>
function display() {
alert(“FirstName is Changed!”);
}
</script>
3.
HTML DOM
The HTML DOM is a standard object model and programming interface for HTML. The HTML DOM is
a standard for how to get, change, add, or delete HTML elements.
The HTML DOM has two components.
HTML DOM methods: actions you can perform (on HTML Elements).
HTML DOM properties: values (of HTML Elements) that you can set or change.
HTML DOM Document
The HTML DOM document object is the owner of all other objects in your web page. Using HTML
DOM document you can do many things like Creating & Removing an HTML Element.
HTML elements can be found and accessed in an HTML page using DOM.
You can find Elements by
Finding HTML elements by id
Finding HTML elements by tag name
Finding HTML elements by class name
Finding HTML elements by CSS selectors
Finding HTML Element by Id
To find HTML By ID we use keyword – [Link](“sampleID “);
E.g: <p id=”P1”> This is My Paragraph </p>
<script>
var myParagraph = [Link](“P1”); // finding html element by id=P1
//The below code display the content of the paragraph accessed by id.
[Link](“This is the Paragraph Content” + [Link]);
</script>
innerHTML – is used to get the content of HTML element.
Finding HTML Elements by Class Name
To find HTML By Class Name we use keyword – [Link](“sampleClass “);
Note: [Link]() return an HTMLCollection() object. HTMLCollection()
object is an array-like list (collection) of HTML elements. Since there are many HTML elements that can
belong to a single class. Or there are many HTML Elements that share the same class.
Length Property: defines the number of elements in an HTML Collection.
E.g: <p class =”errorMessage” > This is My Paragraph </p>
<p class =”large” > This is My Paragraph </p>
<p class =”errorMessage” > This is My Paragraph </p>
<script>
// finding html element by class Name = “errorMessage”
var errorMessages = [Link](“errorMessage”);
var length = [Link];// returns the number of elements in errorMessages
[Link](“The Number of elements in class errorMessage is =” + length); //length=2
[Link](“Here is the list of error Message contents!”);
//The below code display the content of the HTML elements accessed by Class Name = “errorMessages”
for( var i=0; i<length; i++) {
[Link]( errorMessages[i].innerHTML + “<br>”);
}
</script>
Finding HTML Elements by Tag Name
To find HTML By Tag Name we use keyword – [Link](“sampleClass “);
Note: [Link]() return an HTMLCollection() object.
Length Property: defines the number of elements in an HTML Collection.
E.g: <h1> This is Heading 1 </h1>
<p class =”errorMessage” > This is My Paragraph </p>
<p class =”large” > This is My Paragraph </p>
<p class =”errorMessage” > This is My Paragraph </p>
<script>
// finding html element by Tag Name = “p”
var paragraphs = [Link](“p”);
var length = [Link];// returns the number of paragraph elements
[Link](“The Number of paragraphs in the HTML document is=” + length); //length=3
[Link](“Here is the list of paragraph contents!”);
//The below code display the content of the HTML elements accessed by Tag Name = “P”.
for( var i=0; i<length; i++) {
[Link](paragraphs [i].innerHTML + “<br>”);
}
</script>
Finding HTML Elements by CSS Selectors
To find HTML elements By CSS selector we use keyword – [Link] (“selector“);
We can use CSS selector like id, class names, types, attributes, values of attributes, etc.
Note: document. [Link] () return an HTMLCollection() object.
E.g: <head>
<style>
.large {
font-size: 36px; }
</style>
</head>
<body>
<h1> This is Heading 1 </h1>
<p class =”large” > This is My Paragraph </p>
<script>
// finding html element by class Name = “errorMessage”
var paragraph = [Link](“.large”);
var length = [Link];// returns the number of elements in class= “large”
[Link](“The Number of elements in class large is=” + length); //length=1
[Link](“Here is the list of elements in class large!”);
//The below code display the content of the HTML elements accessed by class Name = “large”.
for ( var i=0; i<length; i++) {
[Link](paragraph [i].innerHTML + “<br>”);
}
</script>
</body>
Changing HTML Elements
The HTML DOM allows JavaScript to change the content of HTML elements.
Changing HTML Content
The easiest way to modify the content of an HTML element is by using the innerHTML property.
Syntax: HTML_Element.innerHTML =”new HTML Content”
Example: <p id=”p1”> This is my Paragraph. </p>
<script>
[Link](“p1”).innerHTML=”My Paragraph Content is changed!”;
//The above code changed the content of the paragraph to “My paragraph content is changed!”
</script>
Changing the Value of an Attribute
To change the value of an HTML attribute,
Syntax: HTML_Element .attribute = new value
Example: 1. <a id=”h” href=”[Link] “> Home </a>
<script>
[Link](“p1”).href=”[Link]”
//The above code changed of href of the link [Link]!”
</script>
2. <img id=”i1” src=”[Link]” width=”200”>
<script>
[Link](“i1”).src=”[Link]”
//The above code changed of src of the image to [Link]”
</script>
Changing HTML Style
To change the style of an HTML element,
Syntax: HTML_Element.[Link] = new style
Example: <p id=”p1”> This is my Paragraph. </p>
<script>
[Link](“p1”).[Link]=”red”;
//The above code changed the color of the paragraph to Red.
[Link](“p1”).[Link]=”32px”;
//The above code changed the font size of the paragraph to 32px.
</script>
Example: <img id=”img1” src=”[Link]” width=”500” height=”500”>
<script>
[Link](“img1”).[Link]=”2px solid red ”;
//The above code changed the border of the image to 2px solid red border
</script>
JavaScript Form Validation
HTML form validation can be done by JavaScript.
To validate forms before submission you can use onsubmit event, which is triggered when a form is
submitted.
We use value property to access the value of inputs.
We use length property to get the length of the value
To access form elements we can use
Syntax: [Link]["FormName"]["FormElement_Name"]; OR
We can access form elements by using their ID.
To validate forms,
1. First define validation method and call it inside onsubmit event.
2. Access the form elements to be validated
3. Validate them using different criteria based on your requirement
4. Display an error message to the user
4. You can change the style of the wrong/error inputs
5. You can clear the wrong styles and error messages after the user inputs correctly
- You can validate using DOM validation methods or you can use custom validation.
Custom Validation
Eg. <form name="form1” action="[Link]" method="post" target="_blank" > validateForm()" >
UserName:
<input type="text" name="firstName" id="fs">
<p class="error"> </p>
Phone:
<input type="Number" name="phone" id="phone">
<p class="error"> </p>
<input type="submit" value="Submit">
</form>
<script>
function validateForm(){
var FirstName= [Link]("fs");
var Phone= [Link]["form1"]["phone"];
var result=true; // let result be true until we get Error.
if([Link]==0 )
{
[Link]="wrongInput";
[Link]="UserName Cannot be Empty!";
result=false;
}
if([Link]==0 )
{
[Link]="wrongInput";
[Link]="UserName Cannot be Empty!";
result=false;
}
return result;
}
</script>
Validating using DOM methods
We have different DOM Properties for validation
checkValidity() - returns true if an input element contains valid data
validationMessage - Contains the message a browser will display when the validity is
false.
Example : <input id="id1" type="number" min="10" max="100" required>
<button ><p id="errorMessage"></p>
<script>
function myFunction() {
var input = [Link]("id1");
if (![Link]()) {
[Link]("errorMessage ").innerHTML = [Link];
}
}
</script>