CISC103, Fall 2006, JavaScript Example
Some notes about this page
- The
<form>
element has three <input>
elements, with the names price
, tax
, and total
.
- For each of these input elements, there is a JavaScript object. These objects can be referred to as follows:
window.document.forms[0].price
window.document.forms[0].tax
window.document.forms[0].total
- Note that
forms[0]
means "the first <form>
element listed in the document". The [0]
is because JavaScript always starts counting from 0, not from 1.
- When the button is pressed, the custom function
computeTax()
is called.
- The
computeTax()
function uses the built-in function parseFloat()
to convert the value that comes from the price
object (an <input> element inside the <form> element into a numeric, and then store that value into a variable called purchasePrice
.
- We then calcuate the tax by multiplying the variable
purchasePrice
by .06 (a numeric literal)
- We then store the result back into the values of the two
<input>
elements in the <form>
, tax
and total
- the
<input>
elements tax
and total
are marked readonly
---because they aren't really used for input
- we are using them as a place to display some results on our web page.
Some things we are not doing here, that we could be
- The fields don't line up nicely. We could use a <table> element, or CSS with positioning to fix that.
- We aren't formatting the numbers nicely with a dollar amount, and two decimal places for the cents. There are built-in functions we could call to fix that also.
- If we put in something that isn't numeric for the price, we end up with
NaN
in the tax and total fields. We could put in some code to check for that, and put zeros or blanks in those fields instead.