最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calculate equation like excel jquery - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question edited May 13, 2016 at 11:04 Shijin TR asked Feb 26, 2014 at 7:22 Shijin TRShijin TR 7,76811 gold badges62 silver badges125 bronze badges 4
  • You will need to split the expression on none alphanumeric characters and start from there. – Eric Herlitz Commented Feb 26, 2014 at 7:25
  • 1 A nice question but it wont be something as simple as executing a simple equation, you ll have to write a parser to first separate all the operators and operands – Hanky Panky Commented Feb 26, 2014 at 7:25
  • Do you mean the second refers to the data-row? – Nimnam1 Commented Feb 26, 2014 at 7:37
  • @Nimnam1 Yes......... – Shijin TR Commented Feb 26, 2014 at 8:31
Add a comment  | 

5 Answers 5

Reset to default 5

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>

With substrings:

var math_it_up = {
    '+': function (x, y) { return x + y },
    '-': function (x, y) { return x - y },
    '*': function (x, y) { return x * y },
    '/': function (x, y) { return x / y }
};

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

function calculate(equation){
    result=0;
    index=2;

    var value1 = $('input[data-column="'+equation.substring(0,1)+'"]
[data-row="'+equation.substring(1,2)+'"]').val();

    result = parseInt(value1);

    while(equation.substring(index,index+1) !== "") {
        var operator = equation.substring(index, index+1);

        var value = $('input[data-column="'+equation.substring(index + 1, index+2)+'"]
[data-row="'+equation.substring(index + 2, index+3)+'"]').val();

        result = math_it_up[operator](result, parseInt(value));

        index += 3;
    }

    return result;
}

I used math_it_up function from How can I convert a string into a math operator in javascript

You can enlarge operators by adding yours(e.g modulo). Note that I didn't check if value1 or value is a valid number.

FIDDLE

This is an alternate method to using the eval function. To implement this fully with all the mathematical operations is probably more work than it's worth so be advised there but here's a simplistic implementation. fiddle

function calculate(equation){
    var vals = getValues(equation),
        operators = getOperators(equation),
        num1 = vals[0];
    for(var i=0; i<operators.length; i++){
        // simplistic you'll need to be more careful of order of operations
        // if you're going to be using things other than addition and subtraction
        num1 = calculateOperation(operators[i], num1, vals[i+1]);
    }
    return num1;
}

function calculateOperation(op, num1, num2){
    // add more ops as necessary
    if (op === '+'){
        return num1 + num2;
    } else if (op === '-'){
        return num1 - num2;
    }
}

function getValues(eq){
    // use regex because there might be more than one character denoting a row or column
    var column, row,
        operatorRegex = /[\+|\-]/;
        return eq.split(operatorRegex).map(function(identifier){
            column = identifier.replace(/[0-9]+/, "");
            row = identifier.replace(/[A-Za-z]+/, "");
            return parseInt($('[data-column="'+column+'"][data-row="'+row+'"]').val(), 10);
        });
}

function getOperators(eq){
     var ops = eq.split(/[A-Za-z0-9]+/);
     // remove the quotes and return
     return ops.slice(1, ops.length-1);
}

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

You can definitely using this plugin https://github.com/xsanisty/jquery-calx

I create this while ago, and still maintaining it, but instead of data-column and data-equation, mine using data-cell and data-formula

<form id="sheet">
    <input type="text" data-cell="A1" />
    <input type="text" data-cell="A2" />
    <input type="text" data-cell="A3" data-formula="A1*A2" />
</form>

and just need to initiate the plugin

<script>
    $('#sheet').calx()
</script>

and now, it should calculate all the formula defined inside the #sheet, you can even use a lot of excel compatible formula in it

it can be done with eval() function:

$(function(){
    $("input").each(function(){
        var col = $(this).data("column");
        var row = $(this).data("row");
        var val = $(this).val();
        var equation = $(this).data("equation");

        if(equation == undefined)
        {
            eval(col+row+"="+val);
        }
        else
        {
            $(this).val(eval(equation));
        }
    });
});
发布评论

评论列表(0)

  1. 暂无评论