JavaScript Forms
By Herbert J. Bernstein
© Copyright 2004 Herbert J. Bernstein
Managing Forms with JavaScript
Web pages can use JavaScript to manage forms, either
to check and filter input before sending it to
a cgi-bin script to perform the form actions on
a server, or by doing the processing completely
on the client side.
- Organizing the pieces
- Define the functions to do the processing within the head of the page
- Use the name= attribute to provide identifiers for the forms
and the elements within
- Use the onClick= attribute to execute JavaScript code
when a button is clicked
- Use the onFocus= and onChange= to execute
JavaScript code when an input area or text area is selected or changed
- Use the onSubmit= to intercept a form before it
is submitted to a cgi-bin script and the submit() method to submit it.
- Forms
- Forms are aggregations of HTML elements that provide data values
- Each element in a form has a distinct name (the name=
attribute).
- The element names with their values can be sent as a group to a
server for processing
- The individual element names and values are visible to
Javascript code
- See
JavaScript Coder HTML Form Tutorial
- Events
- Processing can be trigged by a variety of events involving forms
- onSubmit -- event happens when the form is submitted
- onReset -- event happens when the form is reset (cleared)
- onFocus -- event happens when an element is given focus (selected)
- onBlur -- event happens when an element loses focus (another element
selected)
- onChange -- event happens when the value of an element changes
- Each possible event name is an attribute of the tag defining the
form or element. The value of the attribute is a fragment of JavaScript code
as a String.
<form name="my_form">
Temperature °F:
<input type="text" name="tempF" size=30 value="68"
onChange="xtempF = parseFloat(document.my_form.tempF.value);
xtempK = ((xtempF - 32)*5)/9 + 273.15; //convert to degrees Kelvin
xtempK = (Math.round(xtempK*100))/100; //round to the nearest 1/100th
document.my_form.tempK.value = xtempK;"></input>
<br>
Temperature °K:
<input type="text" name="tempK" size=30 value=" "
onChange="xtempK = parseFloat(document.my_form.tempK.value);
xtempF = ((xtempK - 273.15)*9)/5 + 32; //convert to degrees F
xtempF = (Math.round(xtempF*100))/100; //round to the nearest 1/100th
document.my_form.tempF.value = xtempF;"></input>
</form>
<P>
Prepared by Herbert J. Bernstein
27 October 2004.
© 2004 Herbert J. Bernstein. All Rights
Reserved.