Press ESC to close

JavaScript calculator

0 2231

In this article, we create a simple calculator with JavaScript, to further explain the getElementById () method.

This is also a simple exercise proposed for educational purposes, later we will develop the same exercise using jQuery.

JavaScript calculator – development

The simple calculator example we’re going to make today uses HTML, CSS, and even JavaScript.

Here is the example.

Enter the numbers and operations by clicking on the buttons and finally click on the equal button (=) to get the result of the operation. Now you can continue to operate on the number obtained or, if you want to delete all the contents of the display, click on the C button.

First we create the HTML code to insert the keys from 0 to 9, then we insert the buttons for the mathematical operations, the key for the comma, the C key and finally the equal key. We also insert the display at the top.

We will then use the div tags, the input tags and the button tag, to which we will assign appropriate classes, to format our calculator with JavaScript, as shown in the example above.

  

We also note that, at the onclick event for the keys, we entered n (this.id), in this way we automatically retrieve the id that is declared in each input. While the onclick event of button we assign the function operation () that we will create in JavaScript.

We then create the style sheet.


.content {
            margin-left: 2px;
        }
.key{
            background-color: #a5cff3 ;
            color: #175c97;
            font-size: 22pt;
            border: none;
            margin: 4px 2px;
            height: 40px;
	    width: 46px;
        }
.display {
            background: none;
            color: #175c97;
            font-size: 24pt;
            border: #175c97 solid 2px;
            margin: 4px 2px;
            width: 204px;
            height: 40px;            
        }
.egual{
            width: 208px;
        }

Of course, you can customize your calculator with JavaScript with the desired formatting.

Finally we implement the JavaScript code.

The code is really very simple. We create the function n (data) which from time to time takes the data entered by clicking on the keys as it uses the getElementById () method.

Then we create the function that performs the operations using the eval statement which will return the result of our operation.

Finally we realize the function that simply clears the display.


function n(ops){ 
   document.getElementById("operations").value += ops;
}

function op() { 
   document.getElementById("operations").value = eval(document.getElementById("operations").value); 
}

function reset_all() { 
   document.getElementById("operations").value = ""; 
}

As I told you this is a simple method to create a calculator with JavaScript, you can find many other solutions.

Alcuni link utili

Tutorial JavaScript

Other stories

JavaScript Object

Next Story

Decimal to Binary conversion

Previous Story