Professional Documents
Culture Documents
Lesson 4.2 - JavaScript Lesson
Lesson 4.2 - JavaScript Lesson
Conditional Structure
JavaScript supports conditional statements which are used to perform different actions based on different conditions.
if
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements
conditionally.
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
if...else
The if...else statement is the next form of control statement that allows JavaScript to execute statements in more
controlled way.
var age = 15;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}else{
document.write("<b>Does not qualify for driving</b>");
}
if...else if...
The if...else if... statement is the one level advance form of control statement that allows JavaScript to make correct
decision out of several conditions.
var book = "maths";
if( book == "history" ){
document.write("<b>History Book</b>");
}else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}else{
document.write("<b>Unknown Book</b>");
}
Switch…case
The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute
based on the value of the expression. The interpreter checks each case against the value of the expression until a match is
found. If nothing matches, a default condition will be used.
var grade='A';
switch (grade)
{
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
default: document.write("Unknown grade<br />")
}
The break statements indicate to the interpreter the end of that particular case. If they were omitted, the interpreter
would continue executing each statement in each of the following cases.
1
Introduction to JavaScript - II
Loop Structures
while
The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once
expression becomes false, the loop will be exited.
var count = 0;
while (count < 10){
document.write("Current Count : " + count + "<br />");
count++;
}
do...while
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This
means that the loop will always be executed at least once, even if the condition is false.
var count = 0;
do{
document.write("Current Count : " + count + "<br />");
count++;
}while (count < 0);
for
The for loop is the most compact form of looping and includes the following three important parts:
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed
before the loop begins.
The test statement which will test if the given condition is true or not. If condition is true then code given inside the
loop will be executed otherwise loop will come out.
The iteration statement where you can increase or decrease your counter.
var count;
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
Loop Controls
break
The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of
the enclosing curly braces.
var x = 1;
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
continue
The continue statement tells the interpreter to immediately start the next iteration of the loop and skip remaining code
block.
2
Introduction to JavaScript - II
var x = 1;
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skill rest of the loop body
}
document.write( x + "<br />");
}
String Object
The String object is used for storing and manipulating text. String indexes are zero-based, which means the first character
is [0], the second is [1], and so on.
You can use quotes inside a string, as long as they don't match the quotes surrounding the string or you can put quotes
inside a string by using the \ escape character.
var answer='It\'s alright';
var answer="He is called \"Johnny\"";
String Length
The length of a string (a string object) is found in the built in property length.
var txt="Hello World!";
document.write(txt.length);
String Manipulation
The indexOf() method returns the position (as a number) of the first found occurrence of a specified text inside a string
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
The replace() method replaces a specified value with another value in a string.
str="Please visit Microsoft!"
var n=str.replace("Microsoft","SLCV");
The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the
specified number of characters.
3
Introduction to JavaScript - II
var str = "Hello world!";
var res = str.substr(1,4);
To extract characters from the end of the string, use a negative start number.
JavaScript Events
JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page.
onclick
This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your
validation, warning etc., against this event type.
<input type="button" onclick="validate()" value="Submit" />
onsubmit
This is an event that occurs when you try to submit a form. You can put your form validation against this event type.
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
Other Events
There were several events supported by HTML5 and JS. Be sure to check it on the web.
Dialog Boxes
Dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users.
4
Introduction to JavaScript - II
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){ // the user clicked Ok
return true;
} else { // the user clicked Cancel
return false;
}
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a label which you want to
display in the text box and (ii) a default string to display in the text box.
Basic Validation - First of all, the form must be checked to make sure data was entered into each form field that
required it. This would need just loop through each field in the form and check for data.
Data Format Validation - Secondly, the data that is entered must be checked for correct form and value. This
would need to put more logic to test correctness of data.
HTML
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!‐‐ Form validation code will come here ‐‐>
</script>
</head>
<body>
<form action="/cgi‐bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="‐1" selected>[choose yours]</option>
<option value="1">USA</option>
5
Introduction to JavaScript - II
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
6