JavaScript: Forms



Forms go hand-in-hand with JavaScript to enable you to tackle many worthwhile challenges. In this session we will modify the contents of form elements using the event-handlers 'onClick' and 'onChange'. 'onClick' we have used before. 'onChange' handles the event that occurs when a form element changes. If someone types his name into a text box, for example, as soon as he is done and clicks elsewhere, an 'onChange' event is triggered. The form elements are familiar to you from your study of HTML and the event-handlers are a part of HTML, so technically this is not a JavaScript lesson and we do not need the <SCRIPT> tag.

Let's use form elements and these event-handlers to create a calculator that converts distances from miles to kilometers. We use the conversion 1 mile = 1.609 kilometers. We use text boxes (<input type=text>) to hold all the information in the calculator.

To demonstrate how 'onChange' works, let's ask the user what state he is from, and then echo the name of the state back to him in a different text box.

Here is the script:


<p>What state do you reside in?

<input type=text name="state" size=30 onChange="stateResults.value = state.value"><br><p> 

<p>Miles: <input type=text name="miles" size=10>  

<input type=button value=" ---> " name="convert" onClick="kilometers.value = miles.value * 1.609">  

<p>Kilometers: <input type=text name="kilometers" size=10><br>

<p><center><input type=reset></center> <p> 

<p>Dear resident of the state of <input type=text name="stateResults" size=30>, yours is one of the truly great states of this country!

<p style="font-size:8pt">Then again, I say that to everybody.


to see this how this script behaves in a new window.


Note how the 'onClick' event-handler multiplies the miles by 1.609 and puts the result into 'kilometers.value,' where 'kilometers' is the name of the text box that follows the 'Kilometers: ' text.


Note how the 'onChange' event-handler puts the state that the user enters (stored in 'state.value') into 'stateResults.value,' where 'stateResults' is the name of the last form element on the page.


Other Resources

Try these links on forms and event-handlers:

Page Link
Event Handlers
Event Handlers
Forms and JavaScript

or check out one of our reference books, or look for other help on the Web.



Work on either 1) your own web page, or 2) the site.

If you work on, create a calculator for international visitors to the site. The calculator should accept an amount in American dollars and calculate and let the viewer know what that amount equals in Canadian dollars, Euros and Japanese yen. To get the current exchange rates between the U.S. dollar and these 3 currencies, visit

Also, ask the user for her first name. Use 'onChange' to echo her first name in a text box farther down the page. This could look like: "Gretchen, here are the results of the international money conversion: ".

If you work on your own site, implement something similar.