JavaScript Calculators & Code Creators

JavaScript Calculators & Code Creators

I’m a big fan of being able to roll my own tools for some simple tasks. JavaScript gives many options and opportunities for creating simple tools to make life easier for people. Occasionally I’ll have a mathematical formula which I need to use a few times, or I might need to do some repetitive string replacements. While I could use spreadsheets, or one of the more advanced development tools available. Many applications are overkill, or lack portability in a particular workplace environment.

I have created many simple tools/utilities in a number of languages including bash, python, C++ or on occasion even using a spreadsheet. One language which I use when I want to create something very light and portable is javascript (sat in a html file). It will work on most browsers, and in most environments. It can be hosted on a central server, or just opened as a file from a users documents.

Creating a simple calculator

This example is going to provide a bit of a template for taking in some numbers and producing an output from them using javascript in a HTML page. This example is as much HTML as it is JavaScript. There are a few more examples linked to at the end of this post.

Creating the HTML page

For guidance on writing HTML (or reminders for people like me who don’t touch HTML often), head over to w3schools.com, they have many amazing tutorials. Here I’m expecting a basic understanding of HTML (or at least the ability to copy/paste with intuition).

Here I want the most simple html page to frame the rest of what I am creating, a little more time on CSS and HTML and it’s easy to create something more beautiful, and in any suggested company style/colors.

<!doctype html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Calculator Example</title>
    <!-- Note: for inline javascript, the code will go here -->
    <!-- Note: for jsfiddle.net, the code will go in the JavaScript frame -->
  </head>
 <body>
   <h1>Calculator Example</h1>
   <p>Inputs will go here</p>
   <p>An action Button will go here</p>
   <p>Output will be here</p>
  </body>
</html>

Put the above text into a file called calc.html, and it can be opened with a web browser and seen. Or, go see the example on jsfiddle.net: Creating a simple calculator – 0

Adding the input boxes

While there is much that can be taken advantage of in HTML forms (see the examples later on). To take two numbers, we just need two inputs (number boxes). For these boxes we only need to define a few things:

  • ID – Not required in this example, but good practice and gives other options for writing JavaScript references.
  • label – This is displayed with the input on the page (the text can go in the paragraph, but for numerous technical reasons this is a very good habit to get into).
  • name – This identifies the input on the page and in code (an alternative to using an ID).
  • type – In this instance, we will use “number” (prevents anything non numeric being typed in), but there are numerous other types.
  • value – This is the default value. It’s not required, but for the sake of examples/guiding users it’s helpful.

From the page we have so far, replace the paragraph with the text: “Inputs will go here” with the code:

<p>
  <label for="input_a">Input A: </label>
  <input name="input_a" type="number" value="100">
  <br/>
  <label for="input_b">Input B: </label>
  <input name="input_b" type="number" value="5">
</p>

See the example on jsfiddle.net: Creating a simple calculator – 1

A button to execute the code

OK, our code doesn’t exist yet, but we will want a button for that code. This button is just another type of input, and it will need:

  • ID – So it can be identified by code.
  • name – so it can be referenced on the page.
  • type – to identify it as a button.
  • value – this is what the text on the button is going to be.
  • onClick – This is the name of the javascript function to call when clicked. Note: jsfiddle doesn’t like this because of the way it loads the pages so for jsfiddle it’s ignored.

From the page we have so far, replace the paragraph with the text “An action Button will go here” with the code:

<p>
  <input id="runButton" type="button" name="run" value="Run Calculations" onClick="calc()">
</p>

See the example on jsfiddle.net: Creating a simple calculator – 2

It is possible in javascript to have people click on an image or anything else for a more elegant user experience.

Somewhere for the output

Often, I’ll put the output into another form of some sort (I think it looks tidy, even if it’s a little robotic/overly functional in appearance). However a simple paragraph can be sufficient, as long as it can be identified.

For this, all we have to do is give something an ID so that the code can change it’s value. So we just have to update the p tag as below:

<p id="output">
  Output will be here
</p>

See the example on jsfiddle.net: Creating a simple calculator – 3

The code to do the maths

This is where we finally get to javascript code, rather than looking at the HTML which frames it.

For this tutorial, the code is super simple. I’m not here to teach mathematics, instead I’ll just add the two numbers together. There are lots of built in functions and libraries, have a look at the w3schools javascript maths content.

I’m defining two functions, one taking two arguments to do a calculation “my_calculation”, and another which will be called by the button which takes the inputs from the boxes, calls the maths function and puts the result into the output.

function my_calculation(x, y) {
  //This is our super clever maths operation.
  //Note: parseFloat() functions are required in some cases
  //      to make sure the interpreter sees two numbers,
  //      and doesn't concatenate two strings.
  return parseFloat(x) + parseFloat(y);
}

function calc() {
  //This example gets a list of all objects with a name
  //(in this case just one), and picks the first from the list.
  var value_a = document.getElementsByName("input_a")[0].value;
  var value_b = document.getElementsByName("input_b")[0].value;

  //This addresses the object by it's ID, which is cleaner.
  document.getElementById("output").innerText = my_calculation(value_a, value_b);
}

Depending on how we are working through the example there are three variances:

  1. Inline – Everything goes in the “head” section of the HTML document.
  2. External file reference – The code is going to sit in a different file, linked from the html file (this is best for reusing a function in multiple places.
  3. jsfiddle.net JavaScript frame – Thanks to the wonders of jsfiddle.net, the javascript can behave as if it’s imported from an external file but be edited inline in the web interface.

Inline

The code sits in the head portion of the page, between “script” tags. The below will work in jsfiddle.net, if done inline rather than in the javascript window (and the onClick event of the input button will work as normal).

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Calculator Example</title>
    
    <script type="text/javascript" language="JavaScript">
      function my_calculation(x, y) {
        //This is our super clever maths operation.
        //Note: parseFloat() functions are required in some cases
        //      to make sure the interpreter sees two numbers,
        //      and doesn't concatenate two strings.
        return parseFloat(x) + parseFloat(y);
      }

      function calc() {
        //This example gets a list of all objects with a name
        //(in this case just one), and picks the first from the list.
        var value_a = document.getElementsByName("input_a")[0].value;
        var value_b = document.getElementsByName("input_b")[0].value;

        //This addresses the object by it's ID, which is cleaner.
        document.getElementById("output").innerText = my_calculation(value_a, value_b);
      }
    </script>

  </head>

 

External file reference

Where above, I put “script” tags around the code, here the code sits in its own file. The only thing required in the HTML document is a reference where to find the script, which sits in the “script” tag definition.

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Calculator Example</title>

  <script src="js_simple_calc_ext.js"></script>

</head>

The working example can be seen:

jsfiddle

See the example on jsfiddle.net: Creating a simple calculator – 4

The whole script

This can be the start of something very useful:

<!doctype html>
<html lang="en">

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Calculator Example</title>
    
    <script type="text/javascript" language="JavaScript">
      function my_calculation(x, y) {
        //This is our super clever maths operation.
        //Note: parseFloat() functions are required in some cases
        //      to make sure the interpreter sees two numbers,
        //      and doesn't concatenate two strings.
        return parseFloat(x) + parseFloat(y);
      }

      function calc() {
        //This example gets a list of all objects with a name
        //(in this case just one), and picks the first from the list.
        var value_a = document.getElementsByName("input_a")[0].value;
        var value_b = document.getElementsByName("input_b")[0].value;

        //This addresses the object by it's ID, which is cleaner.
        document.getElementById("output").innerText = my_calculation(value_a, value_b);
      }
    </script>

  </head>

  <body>
    <h1>Calculator Example</h1>

    <p>
      <label for="input_a">Input A: </label>
      <input name="input_a" type="number" value="100">
      <br/>
      <label for="input_b">Input B: </label>
      <input name="input_b" type="number" value="5">
    </p>

    <p>
      <input id="runButton" type="button" name="run" value="Run Calculations" onClick="calc()">
    </p>

    <p id="output">
      Output will be here
    </p>

  </body>

</html>

Further Examples

The web is full of examples, and one beauty of JavaScript is that it’s often inline and in clear text (although some places obfuscate it or format it in a space saving way which makes it hard to read). All you have to do is view the page source in your web browser.

A couple of mine are:

  • Simple calculator, this is a variance on the above with more calculations and extended use of forms for input and output.
  • js_string_replace.html – This sits as a standalone file. It allows a user to replace string instances.

I used a variance of the string replace for updating XML files defining projects. I only put the name of the project in once, and a couple of other parameters. The script produced two network file references (where the project code should be), and a number of XML entries which needed to be copied into a couple of different files.

Notes

One of the best online guides for javascript is over at the w3schools JavaScript Tutorial

Tip, if developing/debugging code in chrome, check out the chrome-devtools.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.