Priyanka Maurya Priyanka Maurya - 5 months ago 14
Javascript Question

Solving equation using eval(),equation entered by user on html page

I am want to evaluate the equation entered by the user using eval().To read
the input I am using querySelector but its not working.

<html>
<body>
<div class="row">
<div class="col-lg-12">
<input type="text" name="equation" id="equation" placeholder="enter equation eg: 2+4">
<button type="button" id="button" onclick="evaluate()">Result</button><br>
<div style="width:150px; height:50px; color:red; background-color:white;" id="result">
</div>
</div>
</body>

<script>
function evaluate(){
var input = document.querySelector('#equation');
var inputVal = input.innerHTML;
var btnVal = this.innerHTML;
var r1 = eval(btnVal);
document.getElementById("result").innerHTML=r1;

}
</script>
</html>

Answer

evaluate() is a built-in javascript function

You need to change your function name because when you click on button it is calling javscript evaluate function and not your function.

function Evaluate() {
var input = document.getElementById('equation');
var inputVal = input.value;
var r1 = eval(inputVal);
document.getElementById("result").innerHTML = r1;
}

<button type="button" id="button" onclick="Evaluate()">Result</button><br>