-1

We all know how to get different number values and then make calculations, but what if in the input form you write the formula, let's say: 10 * 2, and you want to extract this information and get the result? It is possible to get this information so the Javascript can interpret this as an operation and do the calculation? How would you do it?

Also, to make it more complicated, what if you only have the operator and the second number, but have to get the first number from another div or input and add it?

I'm not sure if I have been clear. Thanks for the help.

Aman
  • 11
  • 3

1 Answers1

0

Yes, you can do this with eval

But it is not recommended to use because of security concerns. Just don't use eval

const input = document.querySelector("input");
const button = document.querySelector("button");
const p = document.querySelector("p");

button.addEventListener("click", e => {
  const value = input.value;
  p.textContent = eval(value);
})
<input type="text" name="" value="" />
<button type="button" name="button"> get result</button>
<p></p>
DecPK
  • 24,537
  • 6
  • 26
  • 42