The University of Texas at Austin- What Starts Here Changes the World
Services Navigation


Example 4 - Working with Forms

Javascript is well-suited for checking form data and manipulating it if needed. Javascript cannot easily store submitted form information by itself (you would need a server-side script of some kind), but it can perfrom calculations on the client side and check to see a form was properly completed.

This tutorial does not cover how to build Web forms. For information on how to create forms see the Forms Section in Learning to Publish.

Example 4 calculates a total in a form given a price and quantity of an item. We will then extend Example 4 to check if a form field was left blank.

<html>
<head>
<title> Example 4  </title>
</head>
<body>

<h1>ACME t-Shirts</h1>

<form name="example">
<fieldset>
  <legend>T-shirts</legend>
<label for="price">Price: <input type="text" name="price" id="price" /></label><br />
<label for="quantity">Quantity: <input type="text" name="quantity" id="quantity" /></label><br />;
<label for="total">Total: <input type="text" name="total" id="total" /></label><br />
</fieldset>
<input type="button" value="Calculate"
onclick="example.total.value=example.price.value*example.quantity.value" />

</form>



</body>
</html>

This example uses an onclick event to calculate the total when the user clicks the button. The Javascript uses the value property of text fields. Notice that the name of the form is example and the fields are called price, quantity, and total. The contents of a text field in Javascript are referenced by formname.fieldname.value. This value property is a read/write property, which means you can read what's in a text field and write new values to a text field. The work is done by the following statement:

example.total.value=example.price.value*example.quantity.value

Specifically, this means set the value property of the total field in the example form to the product of the value of the price field and the quantity field.

Test Example 4

 


  Updated 2006 August 11
  Comments to www@www.utexas.edu