Javascript Calculator

calculator.js

<script>
var number1;
var number2;
function Validate()
{
number1 = document.getElementById('number1').value;
number2 = document.getElementById('number2').value;
if(number1=='' || number2=='')
{
alert('Please enter both number fields');
return false;
}
}
function Add()
{
var IsValidated = Validate();
if(IsValidated!=false)
{
var result = parseFloat(number1) + parseFloat(number2);
alert("Sum of values you entered: "+result.toFixed(2));
}

}
function Multiply()
{
var IsValidated = Validate();
if(IsValidated!=false)
{
var result = parseFloat(number1) * parseFloat(number2);
alert("Multiplication of values you entered: "+result.toFixed(2));
}
}
function Substract()
{
var IsValidated = Validate();
if(IsValidated!=false)
{
var result = parseFloat(number1) - parseFloat(number2);
alert("Substraction of values you entered: "+result.toFixed(2));
}
}
function Divide()
{
var IsValidated = Validate();
if(IsValidated!=false)
{
var result = parseFloat(number1) / parseFloat(number2);
alert("Dividation of values you entered: "+result.toFixed(2));
}
}
function Mod()
{
var IsValidated = Validate();
if(IsValidated!=false)
{
var result = parseFloat(number1) % parseFloat(number2);
alert("Mod of values you entered: "+result.toFixed(2));
}
}
</script>

calculator.html

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

<form>
<input type="number" required id="number1" placeholder="Number 1">
<input type="number" required id="number2" placeholder="Number 2">
<input type="button" value="Add" onclick="Add()">
<input type="button" value="Multiply" onclick="Multiply()">
<input type="button" value="Substract" onclick="Substract()">
<input type="button" value="Divide" onclick="Divide()">
<input type="button" value="Mod" onclick="Mod()">
</form>

Share This:

Leave a Reply

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