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 viewers 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.
<tr> <td valign=top align=right><tt><b>result</b></td> <td valign=top><input type="text" name="result" size="20"> </td> </tr>
<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 enter 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.
<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 fo 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".
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.
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 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.
<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.
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.
| JavaScript Menu Edits | |
|---|---|
| Volcano Terminology term.html |
|
| |
| Volcanic Places in the USA usa.html |
|
| |
| Volcanic Places on Mars mars.html |
|
| |
| Research Project (navigation document of this framed page) proj_nav.html |
|
| |
where language is:
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://www.hawastsoc.org/solar/' + 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();
}
}
<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.
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:
The Internet Connection at MCLI is
Alan Levine --}
Comments to levine@maricopa.edu
URL: http://www.mcli.dist.maricopa.edu/tut/tut28c.html