JavaScript Simple Multiplier Calculator Improved

This post is part two of the JavaScript Simple Multiplier Calculator post. This is the new and improved version. If the user enters a non-number in either field, the result will be zero instead of NaN. NaN stands for not a number. Also, the size of the boxes are smaller. A third improvement disallows the user to enter anything in the result box.

First Number:
Second number:

The JavaScript code called when you click the button in this post is as follows:

function multiplierCalculator2() {
	var resultNum = 0;
	var firstNum = parseFloat(document.getElementById("firstNumber2").value);
	var secondNum = parseFloat(document.getElementById("secondNumber2").value);
	if (isNaN(firstNum)) firstNum = 0;
	if (isNaN(secondNum)) secondNum = 0;
	resultNum = firstNum * secondNum;
	document.getElementById("resultNumber2").value = resultNum;

The HTML code in this post is shown below. I have changed the id by appending a 2 to the end of the names. I have also set the width of each text box. The function name has been changed to multiplierCalculator2().

<div id="multiplyCalculator2">
First Number: <input type="text" id="firstNumber2" name="firstNumber" value="0" style="width: 200px;" />
Second number: <input type="text" id="secondNumber2" name="secondNumber" value="0" style="width: 200px;" />
<input type="button" value="Multiply Both Numbers" onclick="multiplierCalculator2();" />
<input type="text" id="resultNumber2" readonly="readonly" style="width: 300px;" />

Try entering a number with some text right after it. You will notice that the text is ignored and the number is used in the calculation. If you put some characters in front of a number, the calculator returns a 0 because it tries to evaluate it and returns NaN (Not a Number) and the JavaScript code changes it to zero. Zero multiplied by any number gives zero.

Another idea would be to disallow any character data to be entered in the text boxes, only 0 through 9, the plus sign, the negative sign and the period. You would need to run event code for each key stroke by the user. This opens up a whole other topic for future discussion: jQuery.

Leave a comment

Your email address will not be published. Required fields are marked *