Docstoc

Javascript Examples

Document Sample
Javascript Examples Powered By Docstoc
					                                                              110


                        JavaScript
 An Object Based Scripting language similar in Concept to
  VBScript i.e., it is an interpreted language and supports
  DOM. Thus use of window, document, form, navigator,
  location objects is similar to VBScript.
 Syntax is similar to C language (has less things in common
  with Java Language).
 Arrays and Collections use [ ] brackets instead of ( ).
 Unlike VBScript, JavaScript is case Sensitive.
 Very popular for Client-side Scripting since both Netscape
  and Internet Explorer support JavaScript.
 There are a few versions of this language e.g., Microsoft
  version is referred to as JScript. There is also a standard
  version referred to as ECMAScript.
 JavaScript counts time in milliseconds. The reference point is
  January 1, 1970.
 Variables do not need to be declared but it is a good practice to
  do so. var is used to declare variables (similar to dim in
  VBScript).
 Client side Javascript code can be placed in HTML
  Comments inside a <SCRIPT> tag.
 The default scripting language in a browser is JavaScript.
 + is used to catenate strings.
 Event names are similar to VBScript such as onClick for
  button clicks and onBlur for loosing focus from an element.
 The element object properties are also similar to VBScript
  such as .value for reading data from a text box, .checked to
  see if a check box is checked etc..
 JavaScript provides a set of Math functions such as
  Math.random( ), Math.sine( ), Math.floor(.), Math.ceil( ) etc..
 Each statement in JavaScript should be terminated by a ; (as
  is done in C language)
 Parantheses are required in calling a function.
                                                                               111


Example:
<!-- Clientsc1J.htm -->
<HTML>
 <HEAD>
   <TITLE> Client side scripting - Javascript-Reading Data from Text Boxes </TITLE>
 <SCRIPT LANGUAGE="Javascript">
 <!--
  function ReadData() {
   alert(" Name Entered = " + frmData.txtName.value +
        " ID Entered = " + frmData.txtID.value);
 }
 -->
 </SCRIPT>
 </HEAD>
 <BODY>
   <H2> <CENTER> Client Side Scripting using JSCRIPT </CENTER> </H2>
   <H3> <CENTER> Text Box Attributes and Reading Data From Them </CENTER></H3>
   <HR>
   <FORM NAME=frmData>
    <PRE>
     Name: <INPUT TYPE=TEXT NAME=txtName SIZE=30 MAXLENGTH=28 TABINDEX=1>
     ID : <INPUT TYPE=TEXT NAME=txtID SIZE=15 MAXLENGTH=12 TABINDEX=2>
<INPUT TYPE=BUTTON VALUE="ENTER Data" NAME="cmdEnter" onClick="ReadData();">
<INPUT TYPE=RESET
      NAME=cmdReset VALUE="RESET">
    </PRE>
   </FORM>
 </BODY>
<HTML>




    Use \n instead of VbCrLf or Chr(13) to put a string on the
     next line
                                                                                   112


Example: if statement, reading data from check boxes, “\n”
<!-- Clientsc3J.htm -->
<HTML>
 <HEAD>
   <TITLE> Client side Javascript-Reading Data from Check Boxes </TITLE>
 <SCRIPT LANGUAGE="JavaScript">
 <!--
   function Enter() {
    var strChoice
    if (window.frmData.chkSalad.checked)
      strChoice = "Salad" + "\n" ;
    if (frmData.chkRice.checked == true)
      strChoice = strChoice + "Rice" + "\n" ;
    if (frmData.chkFish.checked == true)
      strChoice = strChoice + "Fish" + "\n" ;
    if (frmData.chkDsrt.checked == true)
      strChoice = strChoice + "Dessert" + "\n" ;
    alert(" Dinner Choices = " + "\n" + strChoice);
  }
 -->
 </SCRIPT>
 </HEAD>
 <BODY>
   <H2> <CENTER> Client Side Scripting </CENTER> </H2>
   <H3> <CENTER> Using the Check Box INPUT CONTROL </CENTER></H3>
   <HR>
   Check the Items You would like in your Dinner
   <FORM NAME=frmData>
     <PRE>
       <INPUT TYPE=CheckBox NAME=chkSalad> Salad
       <INPUT TYPE=CheckBox NAME=chkRice> Rice
       <INPUT TYPE=CheckBox NAME=chkFish CHECKED> Fish
       <INPUT TYPE=CheckBox NAME=chkDsrt> Dessert
     </PRE>
     <INPUT TYPE=BUTTON NAME=cmdEnter VALUE="Submit Choices" onClick="Enter();">
   </FORM>
 </BODY>
<HTML>
                                                                                        113


Example: for loop, arrays in Javascript [ ], reading data from option
buttons. Use new to create your own arrays e.g., a1 = new Array(20);
<!-- Clientsc4J.htm -->
<HTML>
 <HEAD>
  <TITLE> Client side scripting - Javascript Reading Data from Radio Buttons </TITLE>

 <SCRIPT LANGUAGE="JAVASCRIPT">
 <!--
  function cmdSubmit_OnClick() {
    var i, strChoice ;
    for (i = 0; i < window.frmData.optDinnerItem.length; i++) {
       if (window.frmData.optDinnerItem[i].checked==true)
         strChoice = window.frmData.optDinnerItem[i].value + "\n" ;
      }
    for (i = 0; i < window.frmData.optDessertItem.length; i++) {
       if (window.frmData.optDessertItem[i].checked == true)
         strChoice = strChoice + window.frmData.optDessertItem[i].value + "\n" ;
     }
    alert (" Dinner Choices = " + "\n" + strChoice);
  }
 -->
 </SCRIPT>

 </HEAD>
 <BODY>
  <H2> <CENTER> Client Side Scripting </CENTER> </H2>
  <H3> <CENTER> Using the Radio Button Control </CENTER></H3>
  <H4> <CENTER> (Also referred to as Option Button sometimes) </CENTER> </H4>
  <HR>
  <H4> Choose a main Dinner Item </H4>
  <FORM NAME=frmData>
   <PRE>
   Pizza <INPUT TYPE=RADIO NAME=optDinnerItem VALUE="Pizza" CHECKED>
   Steak <INPUT TYPE=RADIO NAME=optDinnerItem VALUE="Steak">
   Fish <INPUT TYPE=RADIO NAME=optDinnerItem VALUE="Fish">
   <HR>
<H4> Choose a Dessert </H4>
   Chocolate Cake <INPUT TYPE=RADIO NAME=optDessertItem VALUE="Chocolate Cake"
CHECKED>
   Cheese Cake <INPUT TYPE=RADIO NAME=optDessertItem VALUE="Cheese Cake">
   Icecream Sundae <INPUT TYPE=RADIO NAME=optDessertItem VALUE="Icecream Sundae">
   <HR>

   <INPUT TYPE=BUTTON VALUE="Submit Dinner and Dessert Choices" NAME="cmdSubmit"
         onClick="cmdSubmit_OnClick();">
  </PRE>
  </FORM>
 </BODY>
<HTML>

Example: “\t”, reading data from a drop down list box.
<!-- Clientsc5J.htm -->
<HTML>
                                                                                      114

 <HEAD>
  <TITLE> Client side scripting - Reading Data from Drop Down List Box </TITLE>
 <SCRIPT LANGUAGE="JAVASCRIPT">
 <!--
 function cmdSubmit_OnClick() {
   var strFruit ;

   strFruit = window.frmData.ddlFruit.value + "\n" ;
   alert(" Fruit Choice = " + "\n" + "\t" + strFruit) ;
  }
 -->
 </SCRIPT>
 </HEAD>
 <BODY>
   <H2> <CENTER> Client Side Scripting </CENTER> </H2>
   <H3> <CENTER> Reading Data from the Drop Down List Box Control </CENTER></H3>
   <H4> <CENTER> (SELECT and OPTION Tags are used to create the List Box)
                                        </CENTER> </H4>
   <HR>
   <H4> Choose a Fruit </H4>
   <FORM NAME=frmData>
    <PRE>
         <SELECT NAME=ddlFruit>
          <OPTION VALUE=Orange> Orange
          <OPTION VALUE=Apple SELECTED> Apple
          <OPTION VALUE=Bannana> Bannana
          <OPTION VALUE=Mango> Mango
         </SELECT>
    <HR>
    <INPUT TYPE=BUTTON VALUE="Submit Fruit Choices" NAME="cmdSubmit"
        onClick="cmdSubmit_OnClick();">
    </PRE>
   </FORM>
 </BODY>
<HTML>


Example: Reading data from a list Box.
<!-- Clientsc6J.htm -->
<HTML>
 <HEAD>
   <TITLE> Client side scripting - Javascript Reading Data from List Box </TITLE>
 <SCRIPT LANGUAGE="JAVASCRIPT">
 <!--
   function cmdSubmit_OnClick() {
    var i, strFruit ;
    strFruit = "";
    for (i=0; i < window.frmData.lstFruit.length; i++) {
           if (window.frmData.lstFruit[i].selected == true)
             strFruit = strFruit + "\t" + window.frmData.lstFruit[i].value + "\n" ;
     }
    alert(" Fruit Choice = " + "\n" + strFruit);
  }
 -->
 </SCRIPT>
                                                                                     115


 </HEAD>
 <BODY>
  <H2> <CENTER> Client Side Scripting </CENTER> </H2>
  <H3> <CENTER> Reading Data from the List Box Control </CENTER></H3>
  <H4> <CENTER> (Use SIZE attribute to change a drop down to a List Box)
                                       </CENTER> </H4>
  <H4> <CENTER> (Use MULTIPLE attribute to allow multiple Selections)
                                       </CENTER> </H4>
  <HR>
  <H4> Choose one or more Fruits </H4>
  <FORM NAME=frmData>
   <PRE>
       <SELECT NAME=lstFruit SIZE=4 MULTIPLE>
        <OPTION VALUE=Orange> Orange
        <OPTION VALUE=Apple SELECTED> Apple
        <OPTION VALUE=Bannana> Bannana
        <OPTION VALUE=Mango> Mango
       </SELECT>
   <HR>

   <INPUT TYPE=BUTTON VALUE="Submit Fruit Choices" NAME="cmdSubmit"
       onClick="cmdSubmit_OnClick();">
   </PRE>
  </FORM>
 </BODY>
<HTML>




Example: Reading data from Text Area. Continuing on multiple lines.
<!-- Clientsc7J.htm -->
<HTML>
 <HEAD>
   <TITLE> Client side scripting - Javascript Reading Data from TEXT AREA </TITLE>
 <SCRIPT LANGUAGE="JAVASCRIPT">
 <!--
  function cmdSubmit_OnClick() {
     alert(" Text typed in Text Area = " + "\n" +
                  window.frmData.txaComments.value);
  }
 -->
 </SCRIPT>

 </HEAD>
 <BODY>
  <H2> <CENTER> Client Side Scripting </CENTER> </H2>
  <H3> <CENTER> Reading Data from the Text Area </CENTER></H3>
  <H4> <CENTER> (Text Area behaves like a multiline Text Box)
                                       </CENTER> </H4>
 <PRE>
 Please provide Some Comments about Our Web Site:
 <FORM NAME=frmData>
   <TEXTAREA NAME=txaComments ROWS=5 COLS=40> Comments:
   </TEXTAREA>
                                                                                              116

  <HR>

   <INPUT TYPE=BUTTON VALUE="Submit Comments" NAME="cmdSubmit"
       onClick="cmdSubmit_OnClick();">
  </FORM>
 </PRE>
 </BODY>
<HTML>


Example: Collecting Filename from File control.
<!-- Clientsc8J.htm -->
<HTML>
 <HEAD>
  <TITLE> Client side scripting - Javascript Collecting Filename from FILE Control </TITLE>

 <SCRIPT LANGUAGE="JAVASCRIPT">
 <!--
  function cmdSubmit_OnClick() {
     alert(" File Selected = " + "\n" +
                   window.frmData.filDatafile.value) ;
  }
 -->
 </SCRIPT>

 </HEAD>
 <BODY>
  <H2> <CENTER> Client Side Scripting </CENTER> </H2>
  <H3> <CENTER> Collecting File Name from FILE type INPUT Control </CENTER></H3>
 <PRE>
 Click on the Button to Show File Open Dialog:
 <FORM NAME=frmData>

  <INPUT TYPE=FILE NAME=filDatafile SIZE=50>

  <HR>

   <INPUT TYPE=BUTTON VALUE="Check File Name Submitted" NAME="cmdSubmit"
      onClick="cmdSubmit_OnClick();">
  </FORM>
 </PRE>
 </BODY>
<HTML>

Example: Image type Submit button (if placed inside a form).
<!-- Clientsc9J.htm -->
<HTML>
 <HEAD>
  <TITLE> Client side scripting - Javascript Image Type Submit Button </TITLE>

 <SCRIPT LANGUAGE="JAVASCRIPT">
 <!--
 function imgPrinter_OnClick() {
    alert(" Image Type Button Attributes = " + "\n" +
               "Source File = " + window.imgPrinter.src + "\n" +
                                                                     117

         "Name = " + window.imgPrinter.name);
  }
 -->
 </SCRIPT>

 </HEAD>
 <BODY>
  <H2> <CENTER> Client Side Scripting </CENTER> </H2>
  <H3> <CENTER> An Image Type SUBMIT Button </CENTER></H3>
 <PRE>
 Click on the Image Button Below to Find its Properties:
   <INPUT TYPE=IMAGE NAME=imgPrinter WIDTH=75 HEIGHT=75 SRC=hp.jpg
      onClick="imgPrinter_OnClick();">

  <HR>
 </PRE>
 </BODY>
<HTML>


Example: Data Validation, parseInt, parseFloat, isNaN functions.
<!-- clientsc11J.htm -->
<HTML>
<HEAD>
   <TITLE> Adder with Data Validation - JavaScript </TITLE>
<SCRIPT LANGUAGE=JAVASCRIPT>
<!--
function cmdAdd_onclick() {
  var v1, v2 ;
  var rs ;
  var v1val, v2val ;
  /* --------------- Read and validate value 1 */
  v1val=parseFloat(window.frmCalc.val1.value) ;
  if (isNaN(v1val))
   {
    alert("You must enter a Number in box1") ;
    frmCalc.val1.value="" ;
    return;
   }

   /* -------------- Read and validate value 2 */
   v2val=parseFloat(window.frmCalc.val2.value) ;
   if (isNaN(v2val))
    {
     alert("You must enter a Number in box2") ;
     frmCalc.val2.value="" ;
     return;
    }
  /* ------ do the calculation */
   rs = v1val + v2val;
   window.frmCalc.RESULT.value = rs ;
 }
-->
</SCRIPT>
</HEAD>
                                                                                         118

<BODY>
 <H1> Web Adder with Data Validation </H1>
 <PRE>
  <FORM NAME=frmCalc method="" action="">
   Value1: <INPUT NAME=val1>
   Value2: <INPUT NAME=val2>
            -----------------
   Result: <INPUT NAME=RESULT>

    <INPUT TYPE=button NAME=cmdAdd value=+ onClick="cmdAdd_onclick();">
  </FORM>
 </PRE>
</BODY>
</HTML>




Example: Writing your own functions.
<!-- Clientsc13J.htm -->
<HTML>
 <HEAD>
  <TITLE> Client side scripting Javascript - Writing your own Subs, Functions </TITLE>

 <SCRIPT LANGUAGE="JAVASCRIPT">
 <!--
  function Find_min(v1,v2,v3) {
 // A simple function to be find the minimum of three numbers
   var min ;
   min = v1;
   if (v2 < min) min = v2 ;
   if (v3 < min) min = v3 ;
   return min;
  }

  function cmdMin_OnClick(){ //Event handler for the Calculate Minimum Button
   var num1, num2, num3;
   num1 = parseInt(frmMin.txtV1.value);
   num2 = parseInt(frmMin.txtV2.value);
   num3 = parseInt(frmMin.txtV3.value);
   var Min;
   Min = Find_min(num1,num2,num3);
   alert("Minimum of Three numbers = " + Min)
 }
 -->
 </SCRIPT>

 </HEAD>
 <BODY>
  <H2> <CENTER> Javascript Client Side Scripting </CENTER> </H2>
  <H3> <CENTER> Writing Your own Functions - Finding Minimum </CENTER></H3>
 <PRE>
 Enter some numbers in the three text boxes, then Click on the
 "Calculate Min" Button to Find the minimum of the three numbers entered:
   <FORM NAME=frmMin>
                                                                                  119

   Enter First Number : <INPUT TYPE=TEXT NAME=txtV1>
   Enter Second Number : <INPUT TYPE=TEXT NAME=txtV2>
   Enter Third Number : <INPUT TYPE=TEXT NAME=txtV3>

 <INPUT TYPE=Button NAME=cmdMin VALUE="Calculate Minimum"
onClick="cmdMin_OnClick();">
 </FORM>
 </PRE>
 </BODY>
<HTML>



Example: Elements collection in a form, for loop.
<!-- Clientsc17J.htm -->
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
function cmdSubmit_OnClick () {
var lcemail,lcComments,lcMsg,lnCount,lcRating;
lcemail = frmGuestBook.txtemail.value ;
lcComments = frmGuestBook.txacomments.value ;
if (lcemail == "")
    alert("You must provide an E-mail address.");
  else if (lcComments == "")
        alert( "You must provide a comment.");
      else {
        for (lncount = 1; lncount <= 6; lncount++) {
          if (document.frmGuestBook.elements[lncount].checked == true) {
             lcRating = document.frmGuestBook.elements[lncount].value ;
             break; }
          }
        lcMsg = "You rated our web site as: " + lcRating + "." + "\n \t" ;
        lcMsg = lcMsg + "Your E-mail address is " + frmGuestBook.txtemail.value
        alert(lcMsg) ;
        alert("Your comments have been submitted.");
      }
 }
-->
</SCRIPT>

<TITLE> Javascript - User Input Examples</TITLE>
<H2>Guest Book</H2>
<H4>What do you think of our Web site? Please provide your comments.</H4>
<HR>
</HEAD>
<BODY>
<FORM NAME="frmGuestBook">
<PRE>
E-mail Address: <INPUT NAME="txtemail" SIZE=40 MAXLENGTH=40 VALUE = "">

Rating: <INPUT TYPE="radio" NAME="rating" VALUE="Excellent" CHECKED> Excellent
     <INPUT TYPE="radio" NAME="rating" VALUE="Very Good" > Very Good
     <INPUT TYPE="radio" NAME="rating" VALUE="Good" > Good
                                                                                120

    <INPUT TYPE="radio" NAME="rating" VALUE="Fair" > Fair
    <INPUT TYPE="radio" NAME="rating" VALUE="Poor" > Poor

General Comments

<TEXTAREA NAME="txacomments" ROWS="5" COLS="80"></TEXTAREA>

<INPUT TYPE="button" NAME="cmdSubmit" VALUE="Submit Comments"
       onClick="cmdSubmit_OnClick();"> <INPUT TYPE="reset" VALUE="Reset">
</PRE>
</FORM>
</BODY>
</HTML>

Exercise: Convert the Vbscript code in Clientsc18.htm to Javascript.


Example: Collecting a response from the user by using the confirm method
of the window object. Note that the window object also provides the alert
function (which is similar to MsgBox in Vbscript) and the prompt function
(similar to InputBox in Vbscript)
<!-- Clientsc21J.htm -->
<!-- An example of a Client-side Javascript code that
     collects a response from the user using confirm function.
     window object supports alert, prompt and confirm methods. -->
<HTML>
 <HEAD>
  <TITLE> confirm Function example</TITLE>
 <SCRIPT LANGUAGE="Javascript">
 <!--
 function cmdTestConfirm_OnClick () {
   var ret;
   ret = confirm("Save file before proceeding");
   if (ret)
     alert("You have opted to save");
   else
     alert("You have decided not to save");
  }
-->
</SCRIPT>
</HEAD>
 <BODY>
   <H3> Test of the Confirm Function in Javascripts </H3>
   <H2> Click on the Test Button to see Message Box </H2>
   <FORM>
     <INPUT NAME="cmdTestConfirm" Type="Button" VALUE="Test Confirm Function"
                onClick="cmdTestConfirm_OnClick();">
   </FORM>
 </BODY>
</HTML>
Example: Use of the prompt function.
<!-- Clientsc22J.htm -->
                                                                            121

<!-- An example of a Client-side Javascript code that uses
    a prompt function to collect info from the user -->
<HTML>
 <HEAD>
  <TITLE> Prompt function Example </TITLE>
 <SCRIPT LANGUAGE="Javascript">
 <!--
 function cmdTestPrompt_OnClick() {
   var ret;
   ret = prompt ("Please enter your name","name please");
   alert("Your name is " + ret);
 }
-->
</SCRIPT>
</HEAD>

<BODY>
  <H3> Prompt function Example (method of the window object) </H3>
  <H2> Click on the Test Button to see Prompt Box </H2>
  <FORM>
   <INPUT NAME="cmdTestInputBox" Type="Button" VALUE="Test Input Box"
       onClick="cmdTestPrompt_OnClick();">
  </FORM>
</BODY>
</HTML>




Javascript String Functions:
     Javascript uses the + operator for catenating strings.
     Often a new operator is used to create strings (although not required)
      e.g., s1 = new String(“hello”);
     toUpperCase( ) converts a string to upper case, toLowerCase( )
      converts a string to lower case.
     If s1 is a string, then s1.substring(2,5) returns a string starting from
      the third character to the sixth character (remember start position is 0).
     s1.length( ) reurns the length of the string.
     pos = s1.indexOf(“hi”,5); will search the s1 string for the string “hi”
      starting from position 6 and return its location if found.
     names = new Array(5); creates an array of strings with indices
      varying from 0 to 4.
     name = “Bill Gates”; nm = name.split(“ “); will create an array of
      strings where nm[0] will contain “Bill” and nm[1] = “Gates”.
    

Example: Use of split function.
<!-- Clientsc24J.htm -->
                                                                           122

<!-- An example of Using built-in String Functions - Javascript -->
<HTML>
<HEAD>
 <TITLE> String Built-in Functions Example </TITLE>
<SCRIPT LANGUAGE="Javascript">
<!--
 function cmdEnter_OnClick() {
    var s1 ;
    s1 = prompt("Please Enter Your Full Name", "String Functions Test");
    nm = s1.split(" ");
    l1 = nm.length; // obtain the size of the array
    if (l1 == 2)
       alert("First Name = " + nm[0] + "\n" +
               "Last Name = " + nm[1]);
    if (l1 == 3)
       alert("First Name = " + nm[0] + "\n" +
               "Middle Name = " + nm[1] + "\n" +
          "Last Name = " + nm[2]);
  }

-->
</SCRIPT>
</HEAD>

<BODY>
  <H3> Javascript String Function Example </H3>
  <H2> Click on the Button below to do some String Processing </H2>
  <HR>
  <INPUT TYPE="button" NAME=cmdEnter VALUE="Test of String Functions"
      onClick="cmdEnter_OnClick();">
</BODY>
</HTML>




Javascript Date and Time Functions
     Javascript measures time in milliseconds. The reference point is
      1/1/1970.
     d1 = new Date( ); returns the date and time.
     Date.parse(“June 25, 1997”) returns a date object with a count of
      milliseconds since 1/1/1970.

Example:
<!-- Clientsc27J.htm -->
<!-- Use of Javascript Date Time Functions -->
<HTML>
<HEAD>
 <TITLE> Date Time Functions Example </TITLE>
<SCRIPT LANGUAGE="Javascript">
<!--
 function cmdTestDate_OnClick() {
   var d1;
                                                                                      123

   d1 = new Date();
   alert("Time = " + d1.getHours() + ":" + d1.getMinutes()+ ":" + d1.getSeconds());
  }
-->
</SCRIPT>

</HEAD>

<BODY>
  <H3> Test of Javascript Date and Time Functions </H3>
  <H2> Click Button to Invoke Date Time Functions </H2>
  <FORM>
   <INPUT NAME="cmdTestDate" Type="Button" VALUE="Test Date and Time"
       onClick="cmdTestDate_OnClick();">
  </FORM>
</BODY>
</HTML>


Example:
<!-- Clientsc29J.htm -->
<!-- Use of Javascript Date difference capabilities -->
<HTML>
 <HEAD>
  <TITLE> Date difference Example </TITLE>
 <SCRIPT LANGUAGE="Javascript">
 <!--
  function cmdEnter_OnClick() {
    var bd;
    bd =new Date(frmBday.txtBday.value);
    now = new Date();
    var y1, m1, d1;
    y1 = Math.floor((now - bd)/(1000 * 60 * 60 * 24 * 365)) ;// age in years
    m1 = Math.floor((now - bd)/(1000 * 60 * 60 * 24 * 365) * 12) ;// age in months
    d1 = Math.floor((now - bd)/(1000 * 60 * 60 * 24)) ;// age in days
    alert("Your age in years = " + y1 + "\n" + "age in months = " + m1 + "\n" +
          "age in days = " + d1);
  }
-->
</SCRIPT>
</HEAD>
 <BODY>
   <H3> Test of JavaScript Date difference Capabilities </H3>
   <HR>
   <FORM Name=frmBday>
   Please enter your Birthday :
   <INPUT Name=txtBday value="">
   <BR>
    <INPUT NAME="cmdEnter" Type="Button" VALUE="Click to Calculate Age"
         onClick="cmdEnter_OnClick();">
   </FORM>
 </BODY>
</HTML>
Example: Switch statement, onLoad event, Math functions.
<!-- Clientsc30J.htm -->
                                                                           124

<HTML>
 <HEAD>
  <!-- Example of Window_Onload Event -->
  <TITLE> A Colorful Start to the Web Page </TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
 function window_onLoad() {
  var colornum, BColor;
  colornum = Math.round(Math.random() * 8);
  alert(colornum);
  switch(colornum) {
    case 0 : BColor = "green"; break;
    case 1 : BColor = "blue"; break;
    case 2 : BColor = "yellow";break;
    case 3 : BColor = "lime"; break;
    case 4 : BColor = "aqua"; break;
    case 5 : BColor = "silver"; break;
    case 6 : BColor = "purple"; break;
    case 7 : BColor = "orange"; break;
   default : BColor = "red";
  }
  document.bgColor = BColor ;
}
-->
</SCRIPT>
 </HEAD>
 <BODY onLoad="window_onLoad();">
 <H2> Possibly a A different Color each time the
        document is loaded or refreshed </H2>
  </BODY>
</HTML>


Example: Mixing Javascript and Vbscript. OnBlur event handling in
Javascript.
<!-- Clientsc31J.htm -->
<HTML>
<HEAD>
 <!-- Addition of OnBlur event handler -->
 <TITLE> Feedbackk on Your Shopping Experience with WebShop.com </TITLE>
<SCRIPT LANGUAGE="Javascript">
<!--
function window_OnLoad() {
 frmFeedback.txtEmail.focus();
}

 function txtEmail_OnBlur() {
   var strEmail;
   strEmail = frmFeedback.txtEmail.value ;
   if (strEmail == "") {
     alert("You must not leave E-mail blank");
     frmFeedback.txtEmail.focus();}
 }
-->
</SCRIPT>
                                                                                      125

<SCRIPT Language = VBSCript>
<!--
Sub cmdSubmit_OnClick
Dim strMail,strComments,strMsg,nCount,strRating
strMail = frmFeedback.txtEmail.Value
strComments = frmFeedback.txaComments.Value

 If Trim(strMail) = "" Then
    MsgBox "You must provide an E-mail address.",16
    Else If Trim(strComments) = "" Then
     MsgBox "You must provide Comments.",16
     Else
       For nCount = 1 TO 6
         If frmFeedback.Elements(nCount).Checked Then
            strRating = frmFeedback.Elements(nCount).Value
            Exit For
         End if
       Next
       strMsg = "You rated our Your Experience as: " & strRating & _
                                                     "." & Chr(10) & Chr(13)
       strMsg = strMsg & "Your E-mail address is " & frmFeedback.txtEmail.Value
       If frmFeedback.shopagain(0).Checked = True Then
               strMsg = strMsg & Chr(13) & Chr(10) & "You will shop again with us "
            Else
               strMsg = strMsg & Chr(13) & Chr(10) & _
                                     "Your shopping experience has been negative"
            End If
       MsgBox strMsg,48
       MsgBox "Your comments have been submitted.",48
     End if
  End if
End Sub
-->
</SCRIPT>
 </HEAD>
 <BODY onLoad="window_OnLoad();">
 <H2> Feedback on Your Shopping Experience with WebShop.com </H2>
 <H3> Please fill out the feedback form below.
     Your comments are highly appreciated </H3>
 <HR>
 <FORM NAME="frmFeedback">
  <PRE>
   <B>E-mail Address:</B> <INPUT NAME="txtEmail" SIZE=35 MAXLENGTH=35 VALUE = ""
                onBlur="txtEmail_OnBlur()">
   <B>Your shopping Experience with WebShop.com has been:</B>
   Rating: <INPUT TYPE="radio" NAME="rating" VALUE="Excellent" CHECKED> Excellent
         <INPUT TYPE="radio" NAME="rating" VALUE="Very Good" > Very Good
         <INPUT TYPE="radio" NAME="rating" VALUE="Good" > Good
         <INPUT TYPE="radio" NAME="rating" VALUE="Fair" > Fair
         <INPUT TYPE="radio" NAME="rating" VALUE="Poor" > Poor

  <B>Would you shop again with us:</B>
               <INPUT TYPE=RADIO NAME="shopagain" CHECKED VALUE=Yes> YES
               <INPUT TYPE=RADIO NAME="shopagain" VALUE=No> NO
  <B>General Comments</B>
                                                                              126

  <TEXTAREA NAME="txaComments" ROWS="5" COLS="60"></TEXTAREA>
  <INPUT TYPE="button" NAME="cmdSubmit" VALUE="Submit Feedback">    <INPUT
                                                TYPE="reset" VALUE="RESET">
 </PRE>
</FORM>
</BODY>
</HTML>

				
DOCUMENT INFO
Description: This is a javascript examples. This document is useful for creating javascript.