Avg. Rating 4.3

Problem

I'd like a user to enter three numbers, say X, Y, & Z. Then the form would do the following: FIRST. Multiply X * Y / 1000 and show the results in a box. THEN. Multiply X *(1+Z) and show the results in another box. (Recipe requested by Harvey Waxman)

Solution

Use JavaScript to gather the values from the form fields, calculate the result, and display them in the page. The values entered in form fields are treated as text, so you need to be careful to convert them to numbers, particularly when addition is involved.

Detailed explanation

Using JavaScript to access the values a user enters in a text input field is very easy as long as the field has a unique ID.

Getting input values from a form

Use document.getElementById() to access the value property of each input field, and store it in a variable. For example, if you have a text field with the ID val1, you can retrieve its value like this:

var val1 = document.getElementById('val1').value;

However, the content of form input fields is always treated as text, so it's a good idea to ensure it's treated as a number by passing the value to parseInt() like this:

var val1 = parseInt(document.getElementById('val1').value);

The parseInt() method ensures the value is treated as an integer (whole number). If you want to allow decimal fractions, use parseFloat() instead like this:

var val1 = parseFloat(document.getElementById('val1').value);

Caution: Performing calculations with decimal fractions can lead to inaccurate results because of problems with the way computers handle floating point numbers. It's better to use whole numbers to perform the main calculation, and then divide the result to get an accurate fraction.

Making sure the input values are numbers

If the user inserts text instead of a number, the value stored in the variable is NaN, which is JavaScript's way of saying "not a number". To test whether a value is not a number, create a conditional statement, and pass the value to the isNaN() method like this:

if (isNaN(val1)) {
    // the value isn't a number
}

Performing calculations

JavaScript performs arithmetic calculations in exactly the same way as you learned at school. The only difference is that an asterisk ( *) replaces the multiplication symbol, and a forward slash ( /) is used for division.

So, assuming X, Y, and Z are stored as val1, val2, and val3, you can multiply X by Y and divide the result by 1000 like this:

val1 * val2 / 1000

Multiplying X by 1 + Z looks like this:

val1 * (1 + val3)

Displaying the result of the calculation

If you want to display the result of the calculation in another form field, you assign the calculation to the value property of the field. For example, if the field has the ID result1, you assign it like this:

var result1 = document.getElementById('result1');
result1.value = val1 * val2 / 1000;

On the other hand, if you want to display the result as text alongside one of the input fields, create an empty <span> like this:

<input type="text" name="val2" id="val2"><span id="result1"></span>

You can then display the result inside the <span> by assigning it to its innerHTML property like this:

result1.innerHTML = 'X x Y / 1000 = ' + val1 * val2 / 1000;

Putting it all together

Create a form with three input fields and a button, with two empty <span> tags alongside the last two fields:

<form name="form1" method="post" action="">
  <p>
    <label for="val1">X</label>
    <input type="text" name="val1" id="val1">
  </p>
  <p>
    <label for="val2">Y</label>
    <input type="text" name="val2" id="val2"><span id="result1"></span>
  </p>
  <p>
    <label for="val3">Z</label>
    <input type="text" name="val3" id="val3"><span id="result2"></span>
  </p>
  <p>
    <input type="button" name="calculate" id="calculate" value="Calculate">
  </p>
</form>

Note that the type attribute of the button should not be submit. It needs to be button. Otherwise the form will be submitted without displaying the result of the calculation.

At the bottom of the page, add the following script block:

<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
    // get the input values
    var val1 = parseInt(document.getElementById('val1').value);
    var val2 = parseInt(document.getElementById('val2').value);
    var val3 = parseInt(document.getElementById('val3').value);
    // get the elements to hold the results
    var result1 = document.getElementById('result1');
    var result2 = document.getElementById('result2');
    // create an empty array to hold error messages
    var msg = [];
    // check each input value, and add an error message
    // to the array if it's not a number
    if (isNaN(val1)) {
        msg.push('X is not a number');
    }
    if (isNaN(val2)) {
        msg.push('Y is not a number');
    }
    if (isNaN(val3)) {
        msg.push('Z is not a number');
    }
    // if the array contains any values, display the error message(s)
    // as a comma-separated string in the first <span> element
    if (msg.length > 0) {
        result1.innerHTML = msg.join(', ');
    } else {
        // otherwise display the results in the <span> elements
        result1.innerHTML = 'X x Y / 1000 = ' + val1 * val2 / 1000;
        result2.innerHTML = 'X x (1 + Z) = ' + val1 * (1 + val3);
    }
};
</script>

The script begins by identifying the button using document.getElementById(), and then assigns an anonymous function to the button's onclick event handler. The comments inside the function explain how it works.

Caution: JavaScript uses the plus sign ( +) not only for addition, but also to join strings (text) and variables. This can cause unexpected results when mixing a calculation with text, as in lines 30 and 31 of the function. Because val1 is followed by the multiplication operator ( *) in both cases, the calculation is performed normally. However, if the first calculation added val1 and val2, the two values would be joined as text, rather than being added. For example, if val1 is 10 and val2 is 20, the result is 1020, not 30. To avoid this, simply enclose the calculation in parentheses like this:

result1.innerHTML = 'X x Y / 1000 = ' + (val1 + val2);  // 30
result1.innerHTML = 'X x Y / 1000 = ' + val1 + val2;    // 1020

Submitting the result of a calculation with the form

Using JavaScript to display the results of a calculation in a web page should be regarded simply as a convenience for the user, because it avoids the need for a round-trip to the server. You should never trust the results of such calculations when saving them to a database or transmitting the form input by email. Always use the values of the original input fields and perform the calculations again on the server side. Users can easily spoof the results of a JavaScript calculation.


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes