Client-Side Scripting with JavaScript


Part 8 - JavaScript and Forms

CGI Data Entry and Validation

HTML forms are primarily used to enter information to be sent to the web server to be processed by a CGI program. JavaScript can be used with the forms to assist in data entry and validation.

This example request a date on a form. The default value is set using a JavaScript program that gets the date (from the client computer) and stores it in the form's date field:

<FORM NAME="newcse" ACTION="cse.cgi"> Date: <INPUT SIZE=8 NAME="tdate"><P> <SCRIPT LANGUAGE="JavaScript"> today = new Date(); dd = today.getDate(); mm = today.getMonth() + 1; yy = today.getYear(); sl = "/"; todaystr = mm + sl + dd + sl + yy; document.newcse.tdate.value = todaystr; </SCRIPT>

Form object document.newcse.tdate.value includes:
document - page object
newcse - form object
tdate - form input field object
value - a property


This example uses JavaScript to set the date, change the items in the select box based on the college that is chosen, copy the sponsor's name, and finally validate the data before the form is submitted:

University Curriculum Committee Course Proposal

Date:
College: Arts & Sciences Business Education
Department:
Sponsor:
Check here if chair and sponsor are the same.
Department Chair:
Example of the function and event handlers used:

<SCRIPT LANGUAGE="JavaScript"> function CopyName() { if (document.newcse.same.checked) {document.newcse.chair.value = document.newcse.sponsor.value;} else if (document.newcse.chair.value == document.newcse.sponsor.value) {document.newcse.chair.value = ""} } </SCRIPT> <FORM NAME="newcse" ACTION="form1.html"> Sponsor: <INPUT TYPE="TEXT" NAME="sponsor" SIZE=45> <INPUT TYPE="CHECKBOX" NAME="same" onClick="CopyName();"> Check here if chair and sponsor are the same. Department Chair: <INPUT TYPE="TEXT" NAME="chair" SIZE=45>

Next Next: More JavaScript Forms