You are on page 1of 6

Introduction to JavaScript - II 

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.


 
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.

 
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 method returns -1 if the specified text is not found.


The lastIndexOf() method starts searching at the end of the string instead of at the beginning.
The match() method can be used to search for a matching content in a string
  
var str="Hello world!";  
   document.write(str.match("world!")); 

The replace() method replaces a specified value with another value in a string.
  
str="Please visit Microsoft!" 
   var n=str.replace("Microsoft","SLCV"); 

A string is converted to upper/lower case with the methods toUpperCase() / toLowerCase().


  
var txt="Hello World!";       // String 
   var txt1=txt.toUpperCase();   // txt1 is txt converted to upper 
   var txt2=txt.toLowerCase();   // txt2 is txt converted to lower 

The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the
specified number of characters.


 
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.

The trim() method removes whitespace from both sides of a string.


  
var str = "       Hello World!        "; 
   alert(str.trim()); 

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> 

onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text as well. The onmouseover event
triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out
from that element.
<div onmouseover="over()" onmouseout="out()"> 
             <h2> This is inside the division </h2> 
       </div> 

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.

Alert Dialog Box


An alert dialog box is mostly used to give a warning message to the users and gives only one button "OK" to select and
proceed.
alert ("This is a warning message!"); 

Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with a second
buttons: Cancel.


 
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; 
       } 

Prompt Dialog Box


The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you to
interact with the user. The user needs to fill in the field and then click OK.
var retVal = prompt("Enter your name : ", "your name here"); 

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.

Javascript Form Validation


JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form
validation generally performs two functions.

 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> 

 
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> 
 

Javascript Form Validation


 
<script type="text/javascript"> 
 
// Form validation code here. 
function validate() 

   if( document.myForm.Name.value == "" ) 
   { 
     alert( "Please provide your name!" ); 
     document.myForm.Name.focus() ; 
     return false; 
   }   
 
   if( document.myForm.EMail.value == "" ) 
   { 
     alert( "Please provide your Email!" ); 
     document.myForm.EMail.focus() ; 
     return false; 
   } 
 
   if( document.myForm.Zip.value == "" ||isNaN( document.myForm.Zip.value ) || 
           document.myForm.Zip.value.length != 5 ) 
   { 
     alert( "Please provide a zip in the format #####." ); 
     document.myForm.Zip.focus() ; 
     return false; 
   } 
 
   if( document.myForm.Country.value == "‐1" ) 
   { 
     alert( "Please provide your country!" ); 
     return false; 
   } 
 
   return true; 

</script> 
 
 


 

You might also like