CDW
CDW

Reputation: 33

How would I calculate something that someone puts in a input field using javascript?

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

Answers (3)

Xotic750
Xotic750

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

c0deNinja
c0deNinja

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);

http://jsfiddle.net/4c6tS/1/

Upvotes: 0

phenomnomnominal
phenomnomnominal

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

Related Questions