Writing HTML | About | FAQ | Alumni | Kudos | References | Tags | Lessons | previous | next |

28c. Form Action by JavaScript

Can't do the CGI stuff?.. Do it with
J a v a S c r i p t

Objectives

After this lesson you will be able to:


Lesson

Note: If you do not have the working documents from the previous lessons, download a copy now.

If you do not have access to a web server or the arcane knowledge for programming CGI, you can still create functional web forms with JavaScript. One advantage is that all of the "work" is done on the viewer's desktop ("client-based") rather than running from a web server-- so there is less back and forth communication across the Internet. Another is that you can create functional web pages that can still work even if you are not connected to the net. And also, JavaScript provides some extra features for checking the validity of entered data before it is processed.

However, there are things JavaScript cannot do-- it cannot write or store any data sent from a web form. Also, JavaScript code must be embedded into a web page, so complex scripts add to the file size (and download time) for your web pages. Also, because the scripts are part of a page, anyone can view the code by looking at the HTML source-- if you create a JavaScript quiz, somewhere in the code you must include the answers!

Finally, you may run into situations where visitors to your web pages have an older browser that does not support JavaScript.

So now we will modify our Volcano Web documents so that they do some form work with JavaScript. The first page is the form we worked on in the previous lesson that via a CGI script calculated an estimated velocity based upon an input height entered into a form field. The math is pretty simple, so this is something that can be easily done with JavaScript.

But rather than having our calculation display its results in a new web page like the CGI script does, we can create a form input text field and have JavaScript insert the calculated value into this field. By doing it this way, the person using the form stays on the same page and can try a series of different numbers.

  1. Open the proj_calc.html file in your text editor.
  2. After the table row that contains the radio buttons for units and above the table row that contains the submit button, add this new table row:
    <tr>
    <td valign=top align=right><tt><b>result</b></td>
    <td valign=top><input type="text" name="result" size="20">
    </td>
    </tr>
    
  3. Now we will write a new JavaScript function that will be placed inside the <HEAD>...</HEAD> like we did in lesson 27c. So inside the <HEAD>...</HEAD> tags add this JavaScript code:
    
    <script language="JavaScript">
    <!--
    /* Velocity Calculation
       Calculates a maximum theoretical velocity based upon an
       input height by equating potential and kinetic energies  */
    
    function calc_vel (form) {
    // Check the input for good values
    	if ( isNaN(form.height.value) || (form.height.value <= 0) ) {
    		alert('The entered height \''+ form.height.value +
    		       '\' is not valid. To complete the calculation, ' +
    		       'the height must be a number greater than 0.');
    		form.result.value = '';
    	} else {
    
    // Assume metric first
    		var gravity = 9.8;
    		var myUnits = 'meters';
    
    // If feet were checked, update the units and gravity constant
    		if (form.units[1].checked) {
    			gravity = 32.0;
    			myUnits = 'feet';
    		}
    
    // Calculate velocity and put results in display field
    		var velocity = parseInt(Math.sqrt( 2 * gravity * form.height.value));
    		form.result.value = velocity + ' ' + myUnits + '/second';
    	}
    
    // return FALSE value so form does not call CGI
    	return false;
    }
    //-->
    </script>
    
We have introduced some things you have not seen before! You do not have to understand them to cut and paste this code, but we will give an overview of what it actually does.

The first part of the code uses a multi-line comment marker, /* ... */ for the description of the script. Our function called "calc_vel" will be sent some information via a parameter (the thing inside the parentheses) called "form"-- this is going to be a JavaScript data structure for all of the things selected or entered in our web page form.

The first thing our script does is to make sure the numbered entered is a good value. So we do a test to see if it is a non-numerical using the NaN JavaScript built-in function for testing if something is "Not a Number" and we test to make sure the number is greater than 0. If the input represented by the value of the height input data sent to us fails either test, we generate an alert message.

Otherwise (after the else) we proceed with the calculation, first assuming the input is in metric units. We then check the status of the radio buttons, and adjust these values if the non-metric units were selected. Then, the script uses more JavaScript built-in function to calculate the answer, returning it in an integer format. We then can put this result into the value of the form field we create in step 2.

The function returns a value of "false" to whatever it was that called this function. In the next step we will see what this means.

The last thing we need to do is to edit our <form> tag so that it sends a request to this new JavaScript function.

  1. Edit the <form> tag to read:
    
    <form method=post
      action="http://www.mcli.dist.maricopa.edu/cgi-bin/tut/energy.pl"
      name="energy" onSubmit="return calc_vel(this)">
      

The onSubmit is a new option for this tag that performs what ever JavaScript is in its quotes when the Submit button for the form is clicked. It does this before making a call to the CGI script in the ACTION= attribute. If the result of calc_vel(this) is true, then the CGI is run; if it is false, then the CGI script is not called. This is the feature that allows you to perform JavaScript before a form is sent off to a CGI script, often so that you can use JavaScript to verify the input data.

Another advantage of combining your code like this is that if for some reason a viewer is using a web browser where JavaScript is not active, it ignores all of the onSubmit code and sends the data to the web server CGI to process.

Sending the calc_vel the parameter this, means "send this function all of the data in my form, the names and values of all of my form elements".

  1. Save and Load the proj.html page in your web browser. Try the new calculation form. If all goes well, it should display the calculation results right into the empty field of the web form. Test what happens if you provide a non-numerical or negative height.

JavaScript Navigation Menus

The next thing we will do with JavaScript is to make it easier to navigate among the pages of our site.

Until now, we have created hypertext links at the top of every page that allow the viewer to go forward, backward one web page in our series, or to return to the index page. We can use web page forms to replace this with drop down menus that permit a viewer to move to any page in our site. This is a very valuable feature in a complex web site, and it reduces the number of pages viewers must navigate to see your content. Drop-down menus also collapse the navigation information into a compact display (compare the space taken up by 25 hypertext links to one drop down menu).

Our approach is to write a general JavaScript function that can go into every document that uses the navigation menus, and then make some minor adjustments to each one.

  1. So inside the <HEAD>...</HEAD> tags add this JavaScript code:
    
    function goPage (newURL) {
    // This function is called from the pop-up menus to transfer to
    // a different page. Ignore the value returned is a null string
    
       	if (newURL != "") {
    
    // skip the menu dividers and reset the menu selection to default
       		if (newURL == "-" ) {
    			resetMenu();
    		} else {
    // send page to designated URL
       			document.location.href = newURL;
       		}
       	}
    }
    
    function resetMenu() {
    // resets the menu selection upon entry to this page
       document.gomenu.selector.selectedIndex = 2;
    }
    

These functions perform three different tasks. If the value sent to function goPage is blank (newURL=""), we do nothing. This is the case if the person selected the page currently in view. The second possibility is that the value is "-", which we will use to indicate a "divider" line in our menus, in which case we will then call a second function, resetMenu() that resets the menu to its default state (in this case, selecting the third item in the menu-- Javascript starts counting things from 0.). And the third case is the one where some action really takes place, transferring the document to the value of the URL.

Let's start with our intro.html file, which already has JavaScript code, so we can just copy the two functions and paste it anywhere before the end of the ending JavaScript tag.

  1. Now we will create the menu. Replace the part of the document that looks like:
    <H5>Volcano Web /
    <A HREF="index1.html">Index</A> /
    <A HREF="term.html">next</A></H5>
    to read:
    
    <form name="gomenu">
    <H5>Volcano Web /
    <select onChange="goPage(this.options[this.selectedIndex].value)" name="selector">
    <option value = "index1.html">Volcano Web</option>
    <option value = "-"> --------------</option>
    <option value = "" selected>Introduction</option>
    <option value = "term.html">Volcano Terminology</option>
    <option value = "usa.html">Volcanic Places in the USA</option>
    <option value = "mars.html">Volcanic Places on Mars</option>
    <option value = "proj.html">Research Project</option>
    </select>
    <noscript>
    <A HREF="index.html">Index</A> /
    <A HREF="term.html">next</A>
    </noscript>
    </form>
    </H5>
    

We have inserted a form named "gomenu" that contains a drop down menu named "selector". The onChange Javascript event is called whenever the menu selection is changed, and if so, it calls the function goPage and sends it the value of whatever is in the value portion of the menu item that corresponds to the selection.

The menu item that corresponds to this page ("introduction") will be selected when the page loads by the selected keyword in the option tag. Also note that the value for this tag is empty, or "", meaning that if this menu item were to be chosen, our JavaScript function will know not to change anything. Finally, we have used a line of dashes below the first item as a menu divider; if this item is selected our JavaScript function calls a second function called resetMenu that simply restores the menu to its initial selection (because we do not want to take any action if the viewer selects the dividing line.

The HTML we put in the <noscript>...<.noscript> tags displays our original HTML links in case the viewer is running a web browser that does not support JavaScript.

Now we will add one more small feature to make our menu fully operational. This piece of code will make sure the menu item corresponding to this page will be reset if the viewer should use the menu to navigate to another page and then use the browser back button to return to this page. Without this feature, the menu would load with the least chosen menu item selected.

  1. Change the <body> tag to read:
    
    <BODY BGCOLOR=#000000 TEXT=#FFFFCC LINK=#33CCFF VLINK=#FF6666 onLoad="resetMenu()">
    
    The onLoad Javascript event is called every time the web page is read into the browser, so that it calls our menu resetting function every time the Introduction page loads.
  2. Save and Reload in your web browser. Test to see that the JavaScript navigation menu works to send you to any of the other web pages it lists.

Now to make our menu navigation complete, you will modify the links in a similar fashion in the other main documents of our Volcano web site, copying the code from steps 1,2, and 3 above. There are a few subtle differences that you will have to make for each one, as summarized in this chart:

JavaScript Menu Edits
Volcano Terminology
term.html
  1. This page has no JavaScript code in it, so you will have to insert the script tags
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    
    and
    //-->
    </SCRIPT>
    around the code in step 1

  2. function resetMenu() reads:
    document.gomenu.selector.selectedIndex = 3;
  3. These lines in the form menu (step 3 above) should read:
    <option value = "intro.html">Introduction</option>
    <option value = "" selected>Volcano Terminology</option>
Volcanic Places in the USA
usa.html
  1. The code in step 1 can be inserted with the other JavaScript code in the HEAD of this document.

  2. function resetMenu() reads:
    document.gomenu.selector.selectedIndex = 4;
  3. These lines in the form menu (step 3 above) should read:
    <option value = "intro.html">Introduction</option>
    <option value = "" selected>Volcanic Places in the USA</option>
Volcanic Places on Mars
mars.html
  1. This page has no JavaScript code in it, so you will have to insert the script tags
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    
    and
    //-->
    </SCRIPT>
    around the code in step 1

  2. function resetMenu() reads:
    document.gomenu.selector.selectedIndex = 5;
  3. These lines in the form menu (step 3 above) should read:
    <option value = "intro.html">Introduction</option>
    <option value = "" selected>Volcanic Places on Mars</option>
Research Project
(navigation document of this framed page)
proj_nav.html
  1. This page has no JavaScript code in it, so you will have to insert the script tags
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    and
    //-->
    </SCRIPT>
    around the code in step 1

  2. Change the line in the function goPage (newURL) function that reads:
    document.location.href = newURL;
    to read:
    parent.document.location.href = newURL;
    which is what needs to be done to make the script work in a framed web page.
  3. function resetMenu() reads:
    document.gomenu.selector.selectedIndex = 6;
  4. These lines in the form menu (step 3 above) should read:
    <option value = "intro.html">Introduction</option>
    <option value = "" selected>Research Project</option>

That was a lot of work!

If all went well, your main web pages should now all be connected by a menu navigation tool that now allows a visitor to your site to jump immediately from one page to the other without having to click through a series of pages in between.

One More JavaScript-Powered Form

Now we will combine a bit of what we have done to create a JavaScript tool to navigate to pages at another web site. We are taking advantage of the well-designed web site structure of the Views of the Solar System site that offers content information on all of the planets that is written in three different languages. By examining the URLs for this site, we can see that they look like:

http://solarviews.com/language/planet.htm

where language is:

  1. eng for English
  2. span for Spanish
  3. portug for Portuguese

and planet is simply the name of the planet (e.g. "mars", "jupiter")

Knowing this, we can create a web form where the viewer can select a planet from a drop down menu, and a language from a set of radio buttons, to view content from this site. This creates a simpler and more compact navigation scheme than a list of hypertext links.

  1. Open the mars.html file in your text editor.
  2. Inside the JavaScript code you created for the navigation menu from the last section, add this new JavaScript function:
    
    function goPlanet () {
    // Function for navigation to different parts of the
    // Views of the Solar System site
    
    // get the planet selected from the menu
    	var planet = document.solar.planets[document.solar.planets.selectedIndex].value;
    
    // make sure valid entry is selected
    	if (planet == "") {
    		alert ('Please select a planet!');
    	} else {
    
    // determine which language button is selected
    		for (i=0; i<3; i++) {
    			if (document.solar.lang[i].checked) {
    				lang = document.solar.lang[i].value;
    				break;
    			}
    		}
    
    // construct the URL for the off-site link
    		var url = 'http://solarviews.com/' + lang + '/' + planet + '.htm';
    
    // open the URL in a new window
    		var planet_window = window.open( url , "planets", "toolbar,status,location,menubar,scrollbars,resizable,width=550,height=450");
    
    // If we are on NetScape, we can bring the window to the front
    		if (navigator.appName.substring(0,8) == "Netscape") planet_window.focus();
    	}
    }
  3. In the BODY of this HTML document, after the one sentence about Olympus Mons, add this HTML and web form:
    
    <p>Compare the volcanic landforms on Mars with the other planets<br>
    <form name="solar">
    <center>
    <table border=0 cellpadding=10 cellspacing=2>
    <tr>
    <td valign=top><select name="planets">
    <option value = "" selected>Select a Planet...</option>
    <option value = "mercury">Mercury</option>
    <option value = "venus">Venus</option>
    <option value = "earth">Earth</option>
    <option value = "mars">Mars</option>
    <option value = "jupiter">Jupiter</option>
    <option value = "saturn">Saturn</option>
    <option value = "uranus">Uranus</option>
    <option value = "neptune">Neptune</option>
    <option value = "pluto">Pluto</option>
    </select>
    </td>
    
    <td valign=top>Show the information in:<br>
    <input type="radio" name="lang" value="eng" checked>English<br>
    <input type="radio" name="lang" value="span">Spanish<br>
    <input type="radio" name="lang" value="portug">Portuguese
    </td>
    <td valign=bottom><input type="button" value="Show Info"
        onClick="goPlanet()"></td>
    </tr>
    </table>
    </center>
    </form>
    
    We have created a new web form that contains a drop down menu with the names of the planets and radio buttons to choose the language to display the content. Our JavaScript function simply takes the form elements as selected, and constructs a proper URL for the external web site that contains this information. As a bonus, it opens this in a new JavaScript window, as we learned in lesson 27c.
  4. Save and Reload in your web browser.

Check Your Work

Compare your web pages with this sample of how it should appear. If your pages are different from the sample or the hypertext links do not work correctly, review the text you entered in the text editor. This lesson has presented a large amount of JavaScript to cut and paste, and it is very easy to make a typographical mistake in this process.

Review

Review topics for this lesson:

  1. What are some advantages about using JavaScript to make your web page forms work? What are some problems in using JavaScript for forms?
  2. Describe an approach for having a JavaScript enabled form that performs a calculation of the average of a series fo numbers that would be entered in a web form.
  3. How can JavaScript and CGI scripts work together in a web form?
  4. What are the essential parts to create your own JavaScript navigation menus?
  5. What is needed to create a JavaScript navigation tool that links to external web sites?

Independent Practice

Try changing the navigation links of your own web pages so that they use JavaScript navigation menus.

This is but a small sampling of what you can do with JavaScript. There are numerous web sites that offer JavaScript code that you can freely copy and use, and you do not even have to understand how it all works (though it helps to know!). Visit some of these sites, and try to find a code sample you can include in your own web pages:

Also, we have created another tutorial/resource called the jClicker, a template that shows you how to easily create a JavaScript slideshow.


Coming Next....

Adding sound, video, animation to your web pages.

GO TO.... | Lesson Index | previous: "Forms: Form Action with email and CGI" | next: "Multimedia in a Page " |

Writing HTML: Lesson 28c: Form Action with JavaScript
©1994-1999 Maricopa Center for Learning and Instruction (MCLI)
Maricopa Community Colleges

The 'net connection at MCLI is Alan Levine
Comments to alan.levine@domail.maricopa.edu

URL: http://www.mcli.dist.maricopa.edu/tut/tut28c.html