Reputation: 33
I need help with a basic text input field calculator. Where if someone puts 1+1 etc. It will answer the problem in another text input field but I can not figure out how to with my code below any help would be appreciated.
function Cal() {
var Num = parseInt(document.getElementById("Numbers").value);
var One = Num;
alert(One);
I only have it where it notifys me the answer.
Upvotes: 1
Views: 319
Reputation: 23472
If you want to avoid using eval
then you can use a library like mathjs
, or roll your own.
An example of it in use, loaded using requirejs
.
HTML
<input id="expression" type="text"></input>
<div id="result">0</div>
Javascript
require.config({
paths: {
mathjs: 'https://raw.github.com/josdejong/mathjs/master/dist/math.min',
}
});
require(['mathjs'], function (mathjs) {
var math = mathjs(),
expression = document.getElementById('expression'),
result = document.getElementById('result');
expression.addEventListener('change', function (e) {
result.textContent = math.eval(e.target.value);
}, false);
});
On jsFiddle
Upvotes: 3
Reputation: 3986
You can use eval
in this situation... something like this could work:
function calculateInput(userInput) {
return eval(string);
}
var userInput = document.getElementById("Numbers").value;
var result = calculateInput(userInput);
alert(result);
Upvotes: 0
Reputation: 5515
You could either write a parser, or use eval
, presuming they input valid JavaScript arithmetic. This is one of the few cases where it is entirely reasonable to use eval
, but you still will need to sanitise their inputs.
Upvotes: 2