Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate equation like excel jquery

I have an HTML like ,

 <table>
  <tr>
    <td><input type="text" data-column="A" value="5" data-row="1" /></td>
    <td><input type="text" data-column="B" value="2" data-row="1" /></td>

  </tr>
 <tr>
    <td><input type="text" value="7" data-column="A" data-row="2" /></td>
    <td><input type="text" value="9" data-column="B" data-row="2" /></td>
</tr>
<tr>
      <th><input type="text" data-column="A" data-row="3"  data-equation="A1+A2-B1" />      </th>
     <th><input type="text" data-column="B" data-row="3"  data-equation="B1+B2"  /></th>
   </tr>

 </table>  

And my javascript like

 $('input').each(function(){
 if($(this).attr('data-equation')!=undefined){
    var equation=$(this).attr('data-equation');
    $(this).val(calculate(equation))
 }
});

function calculate(equation){
  result=0;
  //calculate value and return,i dont know how to calculate
  return result;
} 

I need to calculate the value based on data-equation,In the equation ,First element refer data-column and second refer data-row

Fiddle Demo

like image 474
Shijin TR Avatar asked Feb 26 '14 07:02

Shijin TR


1 Answers

If someone is still looking for similar solution, I'd suggest http://mathjs.org/.

Simple spreadsheet-like example:

jQuery(function($) {

  var calculate = function(n) {
    var expr = n.attr('data-equation')
      , ret  = expr;
    
    if (expr) {
      try {
        ret = math.eval(expr);
      } catch(e) {
        ret = 'Syntax error in equation!';  
      }
    }

    var obj = {};
    obj[n.attr('id')] = ret;
    math.import(obj, { override: true });

    return ret;
  };

  $.fn.equations = function() {

    $(this).each(function() {
      var n = $(this);

      n.focus(function() {
        n.val(n.attr('data-equation'));
      });

      n.blur(function() {
        n.attr('data-equation', n.val());
        n.attr('title', n.val());
        n.val(calculate(n));
      });

      if (!n.attr('data-equation')) {
        n.blur();
      }

      n.val(calculate(n));
    });

  };

  $('input').equations();

});
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Equations</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.5.1/math.min.js"></script>
  </head>
  <body>
    <p>A1: <input type="text" id="A1" value="2+2"/></p>
    <p>A2: <input type="text" id="A2" value="16"/></p>
    <p>A3: <input type="text" id="A3" value="A1+A2"/></p>
  </body>
</html>
like image 165
Rafał Toboła Avatar answered Oct 20 '22 18:10

Rafał Toboła