Tools of the Trade | Getting Started: The Elements of Intranet Style | Intranet FAQ | Intranet Events ]
XML Tutorial | VBScript Tutorial | ASP/IIS | JavaScript Tutorial | HTML/DHTML | Portals | DiscussionBoard ]
Intranet Design Magazine
JavaScript
[ Free Newsletter | Glossary | Case Studies | Intranet Buzz! | Intranet Corner | Intranet Talk ]
[ Perl/CGI FAQ | Content Management | Collaboration | ASPs | Top Intranet Headlines ]
    * [ Home | eXchange | F A Q | Search ]

  •   Home
  •  Getting Started
  •  Intranet Development
  •  Info Management
  •  Columns & Advice
  •  Case Studies
  •  Security
  •  Intranet FAQ
  •  Discussion Board
  •  Events Calendar
  •  Intranet Books
  •  Tools of the Trade
  •  Tutorials
  •  Features
  •  Site Map


Free Newsletter!
 
Privacy Policy

Search
Intranet Journal:




www.internet.com
   

JavaScript Forms and Frames

Enhancing HTML on the Client Side is What Scripting is All About



By Reaz Hoque

The most effective way to understand JavaScript's power is to apply it to forms. JavaScript lets your visitors complete your forms faster than using CGI (Common Gateway Interface). One of the problems with CGI is that when a user makes a mistake filling out a form, he or she has to wait for the server to return an error message. With JavaScript, this process is almost instantaneous. You can set up the form so that when the user clicks on the submit button, JavaScript will check to see if all the input is valid before it sends it to you or your server.

In this column I explain two aspects of JavaScript: working with HTML forms and manipulating frames. Before we start, I suggest you read my earlier tutorial on Javascript Event Handlers. To understand how HTML forms interact with scripts, it helps to have a grasp of the scripting language's event handling features.

We will also give you a simple but effective personalized greeting script and a script used for submitting and HTML form.

This month we cover:

Personalized greetings 
To create this script, we use the JavaScript prompt dialog box. This prompts the user to input his or her name so that you can display it on your page. 

Let's look at the script: 

<HTML>
<HEAD><TITLE>Welcome users by their name</TITLE>
</HEAD>
<body bgcolor=ffffff>
<SCRIPT>
var temp="Input your name";
var user_name=prompt(temp,"web surfer");
if (user_name)
document.write("<h2>Hello  " + user_name + "! Thanks for
visiting!</h2>");
else 
document.write("<h2>Hello and thanks for visiting!</h2>");
</SCRIPT>
</BODY>
</HTML>
See this script work. 

First, we define a variable called temp, which holds the text that will be displayed in the dialog box. 

Then we create a Boolean value called user_name that holds the prompt() method. (The method takes two parameters: the text to be displayed and the default prompt value for the dialog box.) The default value is important to set up; we don't want the variable to hold an undefined value. 

Next, we use an if..else statement, so if the user clicks on the OK button on the dialog box, we print the text, Hello [user name]! Thanks for visiting. Otherwise, if the user clicks on the cancel button, we simply print the text, Hello and thanks for visiting! 

Submitting an HTML form using JavaScript 
Before JavaScript came along, we had to use CGI to submit an HTML form. This was not always easy, since CGI programming can be tricky and not everyone has access to a CGI-bin directory where scripts must be located to run properly. JavaScript provides a simple and fast alternative for form submission. In our next example, we show you how to submit a user feedback form to an e-mail account. 

<HTML>
<HEAD>
<TITLE>Submitting a form Via Email</TITLE>
</HEAD>
<BODY BGCOLOR="ffffff" TEXT="000000">
<H2><u>Submitting a form Via Email</u></H2>

<form METHOD="POST" ENCTYPE="text/plain"
action='mailto:devnull@wpi.com'>
<input type="hidden" name="Type of Form" value="Feedback on
netscapeworld.com">
<b>Your Name</b><BR>
<input type="text" name="Name" SIZE="50" MAXLENGTH="50"><BR>
<b>Your Email:</b><BR>
<input type="text" name="Email" SIZE="50" MAXLENGTH="50"><BR> 
<b>Your Comment:</b><BR>
<textarea name="Comment" wrap=physical rows=7 cols=43></textarea><BR> 


<input type="submit" VALUE="Send Form">
<input type="reset" Value="Reset Form">

</FORM>
</BODY>
</HTML>
See this script work. 

First we created an HTML form using the <FORM> tag. Inside this tag we define two things: the encryption type and the form action. The reason why we define the encryption type to "text/plain" is so that we don't send an encrypted message to an e-mail account. 

For this example, the form action is basically an e-mail address that receives feedback. Make sure you use mailto when using an e-mail to submit the form. 

Next, we create some form elements. These elements should have unique names so that when you receive the form information, you know for which variable the user input the information. Finally, we create a submit and a reset button. As their names suggest, the submit button submits the form (this button is a must!) and the reset button clears the form and restores the default values (if any). 

Input validation 
When your user is filling out a form, you must make sure they input valid data without leaving anything blank, or does not input a numeric value for a text input, or vice versa. Therefore, you need to use an input validation script that will sift through the form before it is sent to you or to the server. 

Let's see an example: 

<HTML>
<HEAD>
<TITLE>Form Validation</TITLE>
<SCRIPT LANGUAGE="JavaScript">

function validate_text1(form){
var input_str=document.forms[0].user_name.value;
var input_len1=input_str.length;
   if(input_len1== 0){
     alert("Input your name!");
     return false;
   }
   else {
   for (var j = 0; j < input_len1; j++) {
     var ch2 = input_str.substring(j, j + 1);
     if (((ch2 < "a") ||  (ch2 > "z")) &&
        ((ch2 < "A") || (ch2 > "Z"))) {
          alert("Input a valid name!");
          return false;
     }
   }
   return true;
} // end function validate_text1

function validate_text2(form) {
   var input_str=document.forms[0].text2.value;
   var input_len2=input_str.length;
   if(input_len2== 0) {
     alert("Input your age!");
     return false;
   }
   else {
     for (var i = 0; i < input_len2; i++) {
       var ch = input_str.substring(i, i + 1);
       if ((ch < "0" )||( ch > "9" )) {
         alert("Input number only for your age!");
         return false;
       }
     }
     if (input_str>150 || input_str<1) {
       alert("Please input a valid age (you must \nbe between
       1-150 years of age)!");
       return false;
     }
   }
   return true;
} // end function validate_text2

function validate_text3(form) {
   var input_str=document.forms[0].text3.value;
   var input_len3=input_str.length;
   if (input_len3==0 || input_str.indexOf ('@', 0) == -1) {
     alert ("Please input a valid e-mail!");
     return false;
   }
   else return true;
} // end function validate_text3

function returnSelection(radioButton) {
   var selection=null;
   for(var i=0; i<radioButton.length; i++) {
     if(radioButton[i].checked) {
       selection=radioButton[i].value;
       return selection;
     }
   }
   return selection; 
} // end function returnSelection

function validate_radio(form) {
   if (returnSelection(document.forms[0].contact) == null) {
     alert("Please select if want to be contacted!");
     return false;
   }
   else return true;
} // function validate_radio

function submitme(form) {
   if(validate_text1(form)
      && validate_text2(form)
      && validate_text3(form)
      && validate_radio(form)) {
      alert("All Inputs are Ok.");
      /*
        Add the following lines to submit the form via e-mail:
        document.forms[0].action="mailto:username@server.com";
        document.forms[0].submit();
      */

      /*
        Add the following lines to submit the form via cgi:
        document.forms[0].action="/cgi-bin/mail.pl";
        document.forms[0].submit();
      */
   }
} // end function submitme

</SCRIPT>
</HEAD>
<BODY BGCOLOR="ffffff" TEXT="000000" >
<H2><u>Input Validation</u></H2>

<form METHOD="POST" ENCTYPE="text/plain" 
onSubmit='submitme(this.form);'>

<b>Your name (Input Only Text):<BR></b>
<input type="text" name="user_name" SIZE="50"
MAXLENGTH="50"><BR>


<b>Your Age(Input Only Numbers):</b><BR>
<input type="text" name="text2" SIZE="50" MAXLENGTH="50"><BR> 

<b>Input Email:</b><BR>
<input type="text" name="text3" SIZE="50" MAXLENGTH="50"><BR> 

<b>Do you want us to contact you?</b><BR>

<input type="radio" name="contact" VALUE="1">Yes

<input type="radio" name="contact" VALUE="0">No
<p>

<input type="submit" VALUE="Send Form">
<input type="reset" Value="Reset Form">

</FORM>
</BODY>
</HTML>
See this script work. 

Wow, this script is long! Let's tear it apart. First, we create a form with five elements: three textbox elements and two buttons. The textboxes take specific data as input. For example, we require that the user inputs only text for name and only a numeric value for age. The submit and reset buttons do as you'd expect. Note that we used the onSubmit event handler, which calls the submitme() function after the user clicks on the submit button. 

On the back-end, we have five other functions besides submitme(). submitme() sees if the functions for each form element returns a true or the inputs for all the elements are valid. If so, then it alerts the user that inputs are okay. Let me walk you through the functions that validate input for each element. 

In the validate_text1() function, first we create a variable that captures the data from the textbox called user_name. Then it finds the length of the data and puts it in another variable called input_len1. An if statement checks to see if the input_len1 is 0 or if there is no input. If so, an alert displays the text, Input your name! and a false value is returned. If there is an input or input_len1 is not 0, we use an else statement. Inside this else statement, we use a loop that walks through each character of inputted value. It checks to see if the input is something between A to Z (upper case and lower case). If the loop finds a character that is not in that range, we alert the user with the text, Input a valid name! and return a false. If the input is valid we simply return a true

The validate_text2() function performs similar tasks as the validate_text1() function, but here we look to see if a non-numeric value was entered and we also check to see if the inputted age is a realistic one. As before, we create two variables: one to capture the value from the textbox called text2 and another to store the length of the inputted data. 

First, we check to see if there is no input. If so, we ask the user to input his or her age. If there is an input we check to see if the data is a numeric value by using a loop (like the one from validate_tex1() function) to see if each character is between 1 and 9. Lastly if the input is a numeric value, we check to see if that value is between 1-150. If not, we alert the user with the text, Please input a valid age (you must be between 1-150 years of age)! Again, if the input is valid we simply return a true

For the validate_text3() function, we take advantage of the indexOf() method in JavaScript. The function checks to see if the @ sign is in the inputted data as all the e-mail addresses must have that sign. We use an if statement to check if there is an input or if the input contains an @ sign. If any of those is false we alert the user saying, Please input a valid address! and return a "false." Otherwise we return a true

The returnSelection() and validate_radio() functions work hand in hand. The returnSelection() function takes the parameter of the radio button of the form (either by name or an array like form.elements[2]) and then it sees if any of the options in the radio option were selected. If so, it returns that selection. The validate_radio() function calls the returnSelection() function to see if the function returns a NULL value or there were no options selected. If that is the case, we alert the user, saying, Please select if you want to be contacted! Otherwise, we return a true

Frames and JavaScript 
Frames offer a way to make your pages look nice. Done properly, frames allow design simplicity and easy navigation. You may already know that in frames. each frame can have its own look and feel. This gives developers the opportunity to create cool pages or abuse common sense. The functionality of JavaScript can make your frame-based page more interactive. You can have a page that has a textbox and use JavaScript to display the inputted data from that textbox to another frame, or you can click on a link and update two frames at the same time. You can also have control buttons in one frame and control the look and feel of other frames. 

In this section, we create a frame-based page where we show you how to: 

  • Update two frames simultaneously with one line 
  • Display a form data from one frame to another frame 
  • Make frame navigation buttons use the navigator history list.

  • (Note that this example needs Netscape Navigator 3.0+ to run.) 
First we create the main frame page that holds together the frames. 
<HTML><HEAD>
<TITLE>Frames and JavaScript</TITLE></HEAD>
<FRAMESET FRAMEBORDER="0" border="0" FRAMESPACING="0" ROWS="72 ,*">
  <FRAME MARGINWIDTH="0" MARGINHEIGHT="0" SRC="top.htm" NAME="top"
NORESIZE SCROLLING="auto">
  <FRAMESET FRAMEBORDER="0" border="0" FRAMESPACING="0"
COLS="15%,70%,15%">
    <FRAME MARGINWIDTH="2" MARGINHEIGHT="0" SRC="left.htm" NAME="left"
NORESIZE SCROLLING="no">
    <FRAME MARGINWIDTH="10" MARGINHEIGHT="5" SRC="center.htm"
NAME="center" scrolling=AUTO>
    <FRAME MARGINWIDTH="10" MARGINHEIGHT="5" SRC="right.htm"
NAME="right" scrolling=no>
  </FRAMESET> </FRAMESET>
<NOFRAME>
You need Netscape 3.0 to visit this site...
</NOFRAME>
</HTML>
Notice that we don't put the frame definition inside the <BODY> tag. As you can see, in our example we are creating a set of frames that has two rows and three columns. The <NOFRAME> tag, by the way lets you display text for browsers that do not support frames. 

The top frame is used to display a banner. The HTML looks like this: 

<HTML>
<HEAD>
<TITLE> Top Frame </TITLE>
</HEAD>
<body bgcolor=tan>
<CENTER>
<IMG NAME="banner" src="top_image.gif" width=400 height=57></CENTER>
</BODY>
</HTML>
The left frame does most of the work for us. Let's look at the file: 
<HTML>
<HEAD>
<SCRIPT>
/*
Let's disable the JavaScript error messages.
(Refer to Intranet Journal's event handler tutorial.)
If you try to click on the submit button when the center frame is
updated from one of the links, you will get a JavaScript error --
you can only update the textbox of center.htm page.
*/
window.onerror=null; 
</SCRIPT>
</HEAD>

<TITLE> Left Frame </TITLE>
<body bgcolor=white><CENTER><BR><BR>
<font size=+1>
Control Box<BR></FONT>
<table colspan=2 border=1>
<tr><td bgcolor="fffffff">
<PRE>
<CENTER>
<a href="http://rhoque.com/book/facts.htm" target="center"
onMouseover="parent.frames[0].document.banner.src='link1.gif'"
onMouseout="parent.frames[0].document.banner.src='top_image.gif'"
onClick='parent.right.location.href="right2.htm"'>Link 1</a>
<a href="http://www.knowledgebase.net" target="center"
onMouseover="parent.frames[0].document.banner.src='link2.gif'"
onMouseout="parent.frames[0].document.banner.src='top_image.gif'"
onClick="parent.right.location.href='right3.htm'">Link 2</a>
</FONT>
</td></tr>

<tr><td bgcolor=#808080>
<CENTER>
<FORM>
<font size=-1 color=white>Input Name:</FONT>
<input type="text" name="user_name" value="" size=10>
<input type="button" value="Submit"
onClick='parent.center.document.forms[0].display_name.value=" Hello "
  + form.user_name.value + "!"'>
<FORM>
</td></tr>

<tr><td bgcolor="fffffff">
<CENTER><BR>
<font size=-1>Frame Navigation</FONT><BR>
<FORM>
<input type="button" value="<<"
onClick='parent.center.history.back()'><input type="button" value=">>"
onClick='parent.center.history.forward()'>
</FORM>
</tr></td>
</TABLE>

</BODY>
</HTML>
First, we create two links. These links are targeted to the center frame, but when you put your mouse over any of the links, the banner from the top frame gets changed. 

Here we need to use special code to change the image on the top frame. You already know that for any objects in an HTML page such as form or frame, JavaScript can refer them by name or an array. In our top.htm page, we create an image object called banner. To replace that image from left.htm page we use the following code: 

parent.frames[0].document.banner.src="[ImgageFileName]"
parent indicates the parent (the frame that holds all the frames together) frame and frames[0] indicates the top frame. 

Now we also use the onClick event handler to update the right-most frame. To change the right frame when the link is clicked on we use the following code: 

onClick="parent.right.location.href='[HTMLFileName]'"
The location.href indicates the URL location for the right frame. 

Next we create a text box and a button. When you click on the button, the textbox from the center frame will get updated (initially it displays nothing). We name the textbox of the center frame display_name (the full listing shown below). To update the textbox of the center frame, after you input your name in the left frame's text box and click on the submit button, you need to use the following code: 

onClick='parent.center.document.forms[0].display_name.value=
"  Hello  " + form.user_name.value + "!"'

All we are doing is making the value of the center frame's textbox equal to Hello [value of user_name]! 

Finally, we have two other buttons that act as the back and forward buttons for frame navigation. They are the same as the "Back" and "forward" button on the Netscape toolbars. We use the JavaScript history object and their back() and forward() methods for this purpose. 

Here is how we set up the HTML page for the center frame: 


<HTML>
<HEAD>
<TITLE> Center Frame </TITLE>
<body bgcolor=black text=red><BR><BR><BR>
<CENTER><PRE>
<H1><u>
C E N T E R  F R A M E
</H1></u><BR><BR>
<FORM>
<input type="text" value="" name="display_name">
</FORM>
</PRE>
</BODY>
</HTML>

And the right frame is set up like this:
<HTML>
<HEAD>
<TITLE> Top Frame </TITLE>
<body bgcolor=white text=blue>
<H1>
<PRE>
R
I
G
H
T

F
R
A
M
E
<PRE></H1>
</BODY>
</HTML>
See the script using frames work. (Excuse the shameless promotion of my book ... it's all I could think of!) 

That wraps up this edition of Intranet Journal's Client-Side Corner. Now go forth and script!


Copyright © 1997 Web Publishing, Inc., an IDG Communications Company. Reprinted with permission from the January 1997 issue of NetscapeWorld magazine, IDG's independent, Web-exclusive magazine for Web developers.


Reaz Hoque is an author, web developer and a speaker. He contributes web-related articles for online and print magazines around the world. Besides IDM, his articles have appeared in ZD Internet Magazine, Web Techniques, Internet World and NetscapeWorld. He wrote Practical Javascript Programming published by MIS press and the upcoming Programming Net Components by McGraw-Hill.  Reaz is scheduled to speak at Software Development ’97 / Web Design ’97 conference in Washington D.C. this fall. For more information, visit Reaz's personal homepage at http://rhoque.com.



   
Of Interest
· Intranet Tools of the Trade
· Intranet Discussion Board




 Intranet News 
* Intranet/Internet Product Summary: January 04, 2001
* Red Herring Picks Plumtree for Employee Portal
* Tideworks Goes with Intranet from Eprise
* Crayfish Nabs 47 Percent of Intranets.com's Japan Arm
* IntraNet Solutions Notches Belt with Oakwood
* BT Secures Corporate Portal Help from Plumtree
* Mobilize Offers Enterprise App to Lexis-Nexis

More News

In' tra net - n. 1) a computer network connecting an affiliated set of clients using standard internet protocols, esp. TCP/IP and HTTP. 2) an IP-based network of nodes behind a firewall, or behind several firewalls connected by secure, possibly virtual, networks.
  IDM Unwired  
IDM on the Road
NOW AN OFFICIAL AVANTGO CHANNEL!
To easily add IDM to your PDA
click here

Featured Archive Articles

  •  Putting Your Intranet to Work: 50 Ideas for Department-Specific Applications
  •   Five-steps to implement your intranet and manage your strategic information
  •  A new generation of intranet tools intersects Customer Relationship Management and Sales Force Automation
  •   Business Intelligence and the Intranet
  •  Effective Intranet Publishing: Getting Critical Knowledge to Any Employee, Anywhere


  •   Using an Intranet to Manage 610,000 animal specimens with Java
  •  Putting JavaScript to Work for Your Intranet
  •   JavaScript Forms and Frames
  •  Introduction to the Browser Object Model
  •  Black Hole Sun: Java is Going Supernova Thanks to its Creator's Gravitational Pull


  •   Managing Large Collections of Documents: A full-length excerpt from the book "Intranet Document Management."
  •  Intranet Traffic Management: Without Quality of Service standards, intranets and extranets face death by success
  •  Issues in Intranet Security: A primer on keeping the keys to the enterprise safe


  •   Report from the trenches: Firms weigh in on intranet deployment trends
  •  The Magna Carta of the Intranet: From Smart Companies, Smart Tools
  •   Prudential HealthCare Launches Extranet to Manage Health Benefits
  •   Wells Fargo Unit Looks To Establish Its Intranet as a 'Portal'
  •   Amkor/Anam's intranet is a study in open systems integration


  •  Tutorial: Finding Your Way Around E-commerce
  •   The Essential Supply Chain
  •  A Definition of Data Warehousing
  •   Internet Messaging: from the Desktop to the Enterprise


  •  Improving Intranet Information Retrieval with Human Indexing
  •   An XML Development Kit
  •   When To Use Active Server Pages
  •  Intranets and extranets for virtual project management
  •  Why Groupware is Hard
  •  Optimizing Web Pages For Handheld Devices


  •  Version Control within a Collaborative Extranet
  •   Electronic Procurement, Extranets and You
  •  Intranet and extranets for virtual project management
  •  Overview of Virtual Private Networks


  •  What's the Future of Application Service Vendors?
  •  'Enterprise Portal' - a New Catch Phrase, But Definitions Vary
  •   Portals, You Say? This One's Private Ericsson's intranet is a give-and-take affair with employees
  •  Application Hosting

Elsewhere on internet.com
*  What Happened at XML 2000?
*  Collaborative Computing: This Changes Everything
*  inFusion: Bringing ColdFusion to a Mail Server Near Youn
*  Netscape 6, Part I: Detection and Scripting
*  AOL Introduces Mobile Communicator
*  NetMenu2
*  Bluetooth Security
*  DHTML Hiermenus 4.0: The Page-Specific Parameters
*  XML Content Syndication: Part 2
*  HardwareCentral Update: Intel's Pentium 4, a New Architecture Unveiled




Copyright 2002 Jupitermedia Corporation, All Rights Reserved.
Legal Notices | Licensing, Reprints, & Permissions | Privacy Policy | Advertising on Intranet Journal
Home | eXchange | F A Q | Find | Register |