Bad Bar Joke
A man walks into a bar with a sandwich on his shoulder.
The bartender turns, looks at him and says, ''Sorry sir, we don't serve food here!!''
Basic Calculation Tutorial
A great thing for beginners to do is to make a simple calculation script. It teaches them how to reference form
elements, use basic math functions, and display information to the user. Here is a simple tutorial to do a
calculation between a field and display the result.
In this example, we are going to calculate the tax rate on an item purchased. Basically it is a simple
multiplication problem.
First you need to create a form where the user can enter in a value. We need a textbox and a button to perform
the calculation when clicked. The button needs an onclick event handler added to it and call a function MyCalc()
which we will make in a bit.
<form name="Form1"> $<input type="text" name="textTotal"> <input type="button" name="btnCalc" value="Calculate Tax" onclick="MyCalc()"> </form>Now we need to build a function called MyCalc(). This function gets called when you click the button.
<script type="text/javascript">
function MyCalc(){
}
</script>
You then need to reference the value in the text box, you do this by referencing the form object.
var val1 = document.formName.elementName.value;
After that we need to do our calculation. You need to parseFloat to turn the form element value from a string to
a number. The reason is if you were to an addition, it would join together instead of increasing in value. For
example, two strings added together would equal "2" + "2" = 22 instead of 2 + 2 = 4.
var amt = 1.06 * parseFloat(val1);
The last step is to display a total, for this we will use an alert.
alert("Your total is $" + amt);
Putting it all together it looks like:
<script type="text/javascript">
function MyCalc(){
var val1 = document.formName.elementName.value;
var amt = 1.06 * parseFloat(val1);
alert("Your total is $" + amt);
}
</script>
Hope that helps you understand a basic JavaScript application.Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages