Yes, this is possible. The easiest way is to use eval();
.
HTML
<input type="text" id="calculator" />
<div id="result"></div>
javascript
var input = document.getElementById('calculator');
var result = document.getElementById('result');
input.addEventListener('keyup', calcular);
function calcular(){
var conta = eval(this.value);
result.innerHTML = conta;
}
Example: link
The above example grabs an event shadow keyup
and runs a function each time a key is released (keyup).
This function runs the eval()
which in the background runs this string as code.
There are other, safer and more labor-intensive ways, which involves regex to detect operators such as division, multiplication, and so on. But I think this example answers the question.
Without eval()
:
I have to leave a parenthesis: eval () is one of the most powerful tools of JavaScript and can be very useful, but in some cases it raises security problems.
02.08.2014 / 17:01