doushi8187 2015-08-14 08:54
浏览 39
已采纳

使用输入的公式计算值

This is my html code :

<input id="R1" type="text" value="100">
<input id="R2" type="text" value="200">
<input id="formula" type="text" value="">
<input type="button" id="save" value="save">

Here the user enter formula value dynamically like R1+R2, (R1-R2)*100. I need to calculate final value using the formula.

Ex: If user enter value in formula field R1+R2; I need the result 300. How do i calculate the value dynamically ?

  • 写回答

5条回答 默认 最新

  • dreamMyDream2014 2015-08-14 09:16
    关注

    Check out this snippet, should work with any combo:

    function calExpression() {
       var f = document.getElementById('formula');
       var inps = document.getElementsByTagName('input');
       var expression = f.value.toUpperCase();//' '+f.value.replace(/([-\/\+\(\)])/g,' $1 ')+' ';
       for (var i = 0; i < inps.length; i++) {
          if (inps[i].id && inps[i].type && inps[i].type.toLowerCase() === 'text') {
              expression = expression.replace(new RegExp('\\b'+inps[i].id+'\\b', 'ig'), inps[i].value);
          }
        }
        eval('f.value = '+expression+';');
    }
    <input id="R1" type="text" value="100">
    <input id="R2" type="text" value="200">
    <input id="formula" type="text" value="">
    <input type="button" id="save" value="save" onclick="calcExpression()">

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)