Basic simple calculator

In this tutorial I am going to show you how to design a basic simple calculator with few HTML codes. Generally building of calculator seems to be very hard work and lots of code. But it is not true when we have powerful markup language like HTML (Hyper Text Markup Language). It requires some few HTML and inline javascript event that handle the calculation. We can start with building a simple form that include a text box for displaying value and remaining other as input button. Let me show you how easily you can do this stuff without any hard coding.

How to design basic simple calculator with HTML

<form name="calc" >
Solution<input type="textfield" name="action" value="">
<br>
<input type="button" value="1" onClick="document.calc.action.value+='1'">
<input type="button" value="2" onClick="document.calc.action.value+='2'">
<input type="button" value="3" onClick="document.calc.action.value+='3'">
<input type="button" value="+" onClick="document.calc.action.value+='+'">
<br>
<input type="button" value="4" onClick="document.calc.action.value+='4'">
<input type="button" value="5" onClick="document.calc.action.value+='5'">
<input type="button" value="6" onClick="document.calc.action.value+='6'">
<input type="button" value="-" onClick="document.calc.action.value+='-'">
<br>
<input type="button" value="7" onClick="document.calc.action.value+='7'">
<input type="button" value="8" onClick="document.calc.action.value+='8'">
<input type="button" value="9" onClick="document.calc.action.value+='9'">
<input type="button" value="*" onClick="document.calc.action.value+='*'">
<br>
<input type="button" value="0" onClick="document.calc.action.value+='0'">
<input type="reset" value="Reset">
<input type="button" value="=" onClick="document.calc.action.value=eval(document.calc.action.value)">
</form>

Basic simple calculator demo

Solution

In this html markup we are creating a form name called calc. So whenever we have to assign a value from the calculator button we have to use the form name concatenating with the name of text box where the addition, division, multiplication and subtraction are performed. So we will use the onClick="document.calc.action.value+='$action_button'" javascript inline action event. See its very easy to embedded the the value of button into the text box. Now we will perform the calculation when user try to click “=” button. This action is also perform by inline javascript event. We will use the onClick="document.calc.action.value=eval(document.calc.action.value)" to calculate the numbers in the text box.

Thanks for reading.
Hope it helps 🙂

Leave a Reply

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