Rushabh Joshi
Rushabh Joshi

Reputation: 233

Evaluate formula with javascript + jquery

ok, I have 3 input text

<input type="text" data-operand="rate">
<input type="text" data-operand="qty">
<input type="text" data-operation="rate*qty">

I have a string of formula like

rate*qty

which i got from input attribute 'data-operation'

now I want to make function like

function(formula) { ... }

which gives me result

and I want to do something like this.

$('input[data-operand="rate"]').val() * $('input[data-operand="qty"]').val()

using jquery javascript library

Upvotes: 0

Views: 1040

Answers (2)

Feugy
Feugy

Reputation: 1918

As far as I understand, you want to apply a dynamic formula to dynamic values.

It's the purpose of the eval() function, or best the Function constructor. For example:

var formulae = new Function('a', 'b', $('[data-operation]').data('opearation'));

function compute() {
  var args = [
    +$('[data-operand=rate]').val(), 
    +$('[data-operand=qty]').val()
  ];
  $('#result').text(formulae.apply({}, args));
}

compute();
$('input').keyup(compute);

See this fiddle

There may be more generic way to declare your arguments (the names and order are significative inside the function constructor).

* EDIT *

If you want to deal with changing number of formulae arguments, you will have difficulties to specify them to the Function constructor. In Javascript, it's very difficult to dynamically invoke a constructor.

But we can use a special property of dynamic functions. See this blue frame in the doc: global variables are accessible.

What you can do is to set your formula's arguments in the global scope (window), and do not specify them as constructor argument.

I updated the fiddle this way. All you have is to add another input, and update your formula.

Upvotes: 1

danwarfel
danwarfel

Reputation: 880

Not sure what your question is, but based on your answer, you either want to actually perform the arithmetic operation, or you want it to serve as a placeholder.

To perform the math, you may need to convert what you get back from .val() into a number. If you're looking for an integer, then use parseInt(). If you're looking for a floating point number (say you're calculating money amounts), then start with parseFloat and clean it up from there.

On the other hand, if you're looking to create a function for values to be dropped into, then set those as parameters for the function and pass in arguments when you call it, like:

function volumeCalc(rate, qty) { var totalVol = (rate * qty); return totalVol; }

Upvotes: 0

Related Questions