How to solve the mathematical expression?
In JavaScript you can solve the mathematical expression easily.
First of all create the form as follow:
<form name="Sample">
<input type="text" size="20" name="calculate">
<input type="button" name="Btn1" value="Calculate" onclick="calc()">
<input type="text" size="20" name="answer">
<input type="reset" name="Btn2" value="Reset">
</form>
Here 'Sample' is the form's name and 'calculate' is the element's name. Both names should be distinct.
Now write the JavaScript as follows:
<script type="text/javascript">
function calc()
{
document.Sample.answer.value = eval(document.Sample.calculate.value)
}
</script>
The key here is the code within the script tag is:
document.Sample.answer.value = eval(document.Sample.calculate.value)
What is eval (something) in this code?
eval (something) is a built in function that "makes sense" of any string you put into it, treating it as code instead of a string.
For Example: If you enter ((3*4+8/2)-6) then output will be 10.
Without using eval (something) what will happen: If you will use the following line of code the expression will not calculate.
document.Sample.answer.value=(document.Sample.calculate.value)
For Example: If you enter ((3*4+8/2)-6) without using eval then output will be "((3*4+8/2)-6)".
For Example:
<html>
<head>
<title>Solve mathematical expression</title>
<script type="text/javascript">
function calc()
{
document.Sample.answer.value=eval(document.Sample.calculate.value)
}
</script>
</head>
<body bgcolor=teal>
<form name="Sample">Enter a mathematical expression in the first box, and than use the calculate button to get the answer.<br />
<table cellpadding="4" cellspacing="0" height=100 width=200 bgcolor=red>
<tr>
<td><input type="text" size="20" name="calculate"></td>
<td><input type="button" name="Btn1" value="Calculate" onclick="calc()"></td>
</tr>
<tr>
<td><b>Answer:</b><input type="text" size="20" name="answer"></td>
<td><input type="reset" name="Btn2" value="Reset"></td>
</tr>
</table>Click on reset button to enter again new expression.
</form>
</body>
</html>
Output: Output of this script will be something like this:

Figure 1: Output of the given script.
Now enter the mathematical expression in the first box and click on the 'calculate' button and get the answer into another box (see following figure).

Figure 2: Solution of the mathematical expression.
There is one small problem with this example: Try inputting letters (i.e. (x*y+z)) into it, and you will get an error message. That's because, of course, you cannot calculate letters, but your code does not know that.