Simple equation solver in JS

This post will let you create a simple equation solver. This program is designed using JS and HTML.
This equation solver can be used to solve addition, division, subtraction or multiplication between two numbers.

Screenshot

Things this code will do
  • Create a Form
  • Take Input from the user
  • A button when click, calls a function
  • Function determines which type of operation and appends the Answer.

The Code
<!--The CSS For the Page-->
<style>
#ans
{
 position: relative;
    text-align: center;
    top: 200;
}
.form
{
 position: relative;
    text-align: -webkit-center;
    padding: 110;
}
.form input[type="text"]
{
 padding: 10 10 2 10;
    border-bottom: 2px;
    border-style: solid;
    border-left: none;
    border-top: none;
    border-right: none;
}
.form input:focus,button:focus{
    outline: 0;
}
.form button
{
 padding: 2;
    background-color: white;
    border-bottom-color: black;
    border-style: solid;
    border-left: none;
    border-right: none;
    border-top: none
}
</style>
<!--The CSS Ends-->
<!--The JS For the Page-->
<script>
function print()
{
 oForm = document.forms["solver"];
 pclass=document.getElementById("ans");
 var s=oForm.elements["f1"].value;
 var res="";
 if(s.indexOf('+') > -1)
 {
  var a,b;
  a=parseInt(s.substring(0,s.indexOf('+')));
  b=parseInt(s.substring(s.indexOf('+')+1,s.len));
  res=a+b;
 }
 else if(s.indexOf('-') > -1)
 {
  var a,b;
  a=parseInt(s.substring(0,s.indexOf('-')));
  b=parseInt(s.substring(s.indexOf('-')+1,s.len));
  res=a-b;
 }
 else if(s.indexOf('*') > -1)
 {
  var a,b;
  a=parseInt(s.substring(0,s.indexOf('*')));
  b=parseInt(s.substring(s.indexOf('*')+1,s.len));
  res=a*b;
 }
 else if(s.indexOf('/') > -1)
 {
  var a,b;
  a=parseInt(s.substring(0,s.indexOf('/')));
  b=parseInt(s.substring(s.indexOf('/')+1,s.len));
  res=a/b;
 }
 else
 {
  alert("Please input a [+|-|/|*] b format");
 }
 pclass.innerHTML=s+"="+res;
 //alert(s+"="+res);
 
}</script>
<!--The JS Ends-->
<!--The HTML For the Page-->
<p id="ans"></p>
<form name="solver" class="form" >
<input type="text" name="f1" id="txt_name" placeholder="Enter The Expression in a+b format." 
size="30" maxlength="70">
<button type="button" onclick="print()">Solve!</button>
</form>
<!--The HTML-->
Got anything to speak ?
Share them here !

Comments

Popular posts from this blog

Non Restoring Division Algorithm Implementation in C

Bit Stuffing Code Implementation in Java

Hackerrank Modified Kaprekar Numbers Solution