Sie sind auf Seite 1von 5

Basics of JavaScript Calculator

Intro
JavaScript (JS) is an HTML markup language, that is, it is used to change the properties of an HTML (or
HTM, PHP, CFM, etc) file. The HTML file is the base page that any web browser supports. This base file
can be stylized for visual appeal using Cascading Style Sheets (CSS), but for this basic example, we will
stick to only JS and HTML. Because JS is an HTML based language, it resides only in the calling webpage.
It makes dynamically controlling webpage content extremely easy, but it does not allow stand-alone
applications to run. You need a webpage and a web browser to make JS run (it is not to be confused
with Java or a Java applet).

It is important to note that some websites (both internally and externally) uses Microsoft’s Internet
Information Services (IIS) server for hosting all websites; IIS 6 was introduced with Windows XP
operating system. As with most software non-open sourced that was introduced in the early 2000’s, this
is a very specific server that was written to primarily server one web-browser. This doesn’t come into
play with basic HTML and JS markup, but this server will not support advanced server-side protocols
such as HTML5 or XHTML5.

Software
1. Simple Notepad for Windows. Text Edit for Mac will not work.
2. Free JavaScript Editor (Windows)
3. KompoZer (Windows and Mac)

Basic Layout
For JS calculators, you need
1. Base HTML document
a. Script tag in Head to call JS code
b. HTML form (with a method=”post”)
c. Output section (preferably using DIVs, but you can also use Tables)
2. JavaScript Code
Base HTML Document
<html>
<head>
<title>New Calculator</title>
1. <script type="text/javascript" src="new_calc.js"></script>
<link rel="stylesheet" type="text/css" href="new_calc.css"/>
</head>
<body>
2. <form name="new_calc" method="post">
3. <input type="text" id="input_1"/>
4. <input type="button" value="Calculate" onclick="myCalc()"/>
</form>
5. <div id="output_1">--</div>
</body>
</html>

1. Declares what file the HTML document will look for to call all JS files
• Needs to be placed in the <head></head> tag of the HTML file
• Should have type="text/javascript", but is not required
• The src="new_calc.js" a tells the HTML to look in the same directory (i.e., same
folder) the current HTML file is located in
• If the file is located in a sub directory, use src="/Inside/new_calc.js"
• If the file is located outside the directory, use
src="../Outside/new_calc.js"
• Use as many ../ as needed to “climb up” the folder hierarchy
2. Declares a form that will take a user’s input and act upon it later
• Needs to have a unique name (will be used by the JS file to locate the proper input field)
• Needs to have method="post" or else JS file will not be able to read the input
3. Creates an input text field that the user can either enter a string or a number
• Does not require an end tag </input>
• Requires a unique id="input_1" so that the JS file can import the text
• For a simple “text” field, does not require type="text", but is proper to include to
make the code unambiguous
4. Creates a “submit” button that will force the JS file to execute
• Needs to include a type="button" to create a clickable button
• The value="Calculate" property places the text "Calculate" inside the button
• The onclick="myCalc()" property will call the JS function "myCalc()" once clicked
• The name "myCalc()" needs to match exactly the function name in the JS file
• Need to include () at the end of the function name
5. Creates a single line in the HTML where the output value of the JS file will be placed
• Needs to have a unique id
• Place this <div> outside of the <form></form> tag
Form Inputs
Below is a list of valid input fields that you can use in a form field:

<form> Defines an HTML form for user input


<input /> Defines an input control
type="text" Defines a one-line input field that a user can enter text into
type="password" Defines a password field
type="radio" User selects ONLY ONE option
type="checkbox" User selects ONE or MORE options
type="submit" Defines a submit button
<textarea> Defines a multi-line text input control
<label> Defines a label for an input element
<fieldset> Defines a border around elements in a form
<legend> Defines a caption for a fieldset element
<select> Defines a select list (drop-down list)
<optgroup> Defines a group of related options in a select list
<option> Defines an option in a select list
<button> Defines a push button

JavaScript File
1. function myCalc(){
//Import/Declare Variables
2. var in_1 = parseFloat(document.new_calc.input_1.value);
3. var out_1;

a. if (validate(in_1) == false){
alert('You need to input a valid number');
exit;
}

//Calculations
4. out_1 = in_1+5;

//Export Results
5. document.getElementById('output_1').innerHTML = out_1;
}

function validate(x){
var y = true;
if (x-0 != parseFloat(x)){
y = false;
}
return y;
}

1. Declares the JS function that will import, calculate, and display outputs
• Needs to begin with function
• Function name has to begin with a letter and cannot include any spaces
• Needs to include ()
• Functions that don’t pass-in any variables have just a ()
• Functions that pass in variables will have variables separated by a comma
• Entire functions are contained between curly brackets "{" & "}"
2. Imports variables from the HTML form
• Declare all variables with var
• Variable names need to begin with a letter and cannot contain any spaces
• Use a single = to assign a value to a variable and == to compare two values in a Boolean
condition
• Ability to declare and import variable in one line
• parseFloat will convert the text inside the text box to a floating point
number. If the user inputs a leter, NaN (not a number) will be returned.
• document references the calling document and the JS file will then look for all
dependencies in that document (the HTML file in our case)
• .new_calc refers to the name of the form in the HTML document
• .input_1 refers to the input of the form
• .value grabs the value from the form’s input field
• ; is required after each line of JS code that does not begin a function, statement
or loop (if, ifelse, for, while, etc.)
3. Declares future variables for unambiguous code and faster rendering.
4. Modifies input variables based on simple math functions
• Allows for the following arithmetic functions: +, -, *, ÷, (, )
• For more advanced math functions, need to use the methods of the Math object (listed
below).
5. Converts the HTML of a specified division <div></div> tag
• document references the calling document and the JS file will then look for all
dependencies in that document (the HTML file in our case)
• getElementById('output_1') searches the HTML document to locate the element
(capitalization is critically important)
• .innerHTML will replace the HTML inside the specified element
a. An if statement that validates input in a text field to make sure it is a number and the field is not
blank. Calls upon custom JS function shown in b.
• The Boolean condition needs to be enclosed in parenthesis
• validate(in_1) calls upon the user-defined validate function and passes in the
variable in_1
• == is the Boolean operator that compares the two sides of the equation for equality
== Equals != Does not Equal
< Less Than > Greater Than
<= Less Than or Equal To >= Greater Than or Equal To
• alert(''); will display an alert box requiring the user to click OK before proceeding
• exit; will stop execution and exit the current function
Methods of the Math Object

The Math object allows for more complicated math than just simple arithmetic.

Math.abs(a) The absolute value of a


Math.acos(a) Arc cosine of a
Math.asin(a) Arc sine of a
Math.atan(a) Arc tangent of a
Math.atan2(a,b) Arc tangent of a/b
Math.ceil(a) Integer closest to a and not less than a
Math.cos(a) Cosine of a
Math.exp(a) Exponent of a
Math.floor(a) Integer closest to and not greater than a
Math.log(a) Log of a base e
Math.max(a,b) The maximum of a and b
Math.min(a,b) The minimum of a and b
Math.pow(a,b) A to the power b
Math.random() Pseudorandom number in the range 0 to 1
Math.round(a) Integer closest to a
Math.sin(a) Sine of a
Math.sqrt(a) Square root of a
Math.tan(a) Tangent of a

References
http://www.w3schools.com/
http://stackoverflow.com/

Das könnte Ihnen auch gefallen