【问题标题】:How to perform calculation with values of dynamic input fields?如何使用动态输入字段的值进行计算?
【发布时间】:2019-07-04 05:22:33
【问题描述】:

我的 html 表单代码有点问题...

在我的代码中,动态生成的输入字段很少。在动态生成的每个输入字段中,都有一些数值。我需要和他们做一些数学计算。

="PE+ROCE+(2-SG)-(4-DY/2)"

这是我的计算模式。其中,PE、ROCE 等是生成的动态输入字段的 ID。

使用生成的动态输入字段的值,我需要执行上述计算。 当用户单击“计算”输入按钮时,必须执行此计算。 然后,上面的最终计算值将显示在我的表单代码底部的输出标签中。 我试图自己解决这个问题。但不幸的是,这项任务失败了。

现在有人可以帮我解决这个问题。 我将不胜感激...

这是我的完整代码..

    // define the headings here, so we can access it globally
    // in the app
    let headings = []

    // appending the created HTML string to the DOM
    function initInputs(headingList) {
      jQuery(".fields").append(createInputsHTML(headingList))
    }

    // the HTMLT template that is going to be appended
    // to the DOM
    function createInputsHTML(headingList) {
      let html = ''
      headingList.forEach(heading => {
        if (heading !== 'Company') {
          html += `<label for="${heading}">${heading}: </label>`
          html += `<input id="${heading}">`
          html += '<br>'
        }
      })

      return html
    }

    // receiving data
    // this data arrives later in the app's lifecycle,
    // so it's the best to return a Promise object
    // that gets resolved (check JS Promise for more information)
    function getJSON() {
      return new Promise(resolve => {
        jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
          resolve(JSON.parse(data))
        });
      })
    }

    // processing raw JSON data
    function processRawData(data) {
      return new Promise(resolve => {
        const companyData = []
        // creating data array
        // handling multiple sheets
        Object.values(data).forEach((sheet, index) => {
          sheet.forEach((company, i) => {
            companyData.push({ ...company
            })
            // create headings only once
            if (index === 0 && i === 0) {
              Object.keys(company).forEach(item => {
                headings.push(item.trim())
              })
            }
          })
        })
        resolve(companyData)
      })
    }

    $(async function() {

      let lists = [];

      function initAutocomplete(list) {
        const thisKey = 'Company'
        $("#company").autocomplete('option', 'source', function(request, response) {
          response(
            list.filter(item => {
              if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
                item.label = item[thisKey]
                return item
              }
            })
          )
        })
      }

      $("#company").autocomplete({
        minLength: 3,
        source: lists,
        focus: function(event, ui) {
          // the "species" is constant - it shouldn't be modified
          $("#company").val(ui.item.Company);
          return false;
        },
        select: function(event, ui) {
          // handling n number of fields / columns
          headings.forEach(heading => {
            $('#' + heading).val(ui.item[heading])
          })
          return false;
        }
      });

      // starting data download, processing and usage
      getJSON()
        .then(json => {
          return processRawData(json)
        })
        .then(data => {
          // just so we see what data we are using
          console.log(data)
          // make the processed data accessible globally
          lists = data
          initAutocomplete(lists)
          initInputs(headings)
        })

    });

  
    
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
    <div class="ui-widget">
      <form id="frm1">
        <label for="company">Company: </label>
        <input id="company"><br />
        <div class="fields"></div>

<input type="submit" id="calculate" value="Calculate">
   
<p>Final Amount <output name="amount" for="calculation">0</output></p>
      </form>
    </div>
    

【问题讨论】:

  • 您在代码的哪一部分执行"A+B+(6-C)+(2-D/3)"
  • 请创建一个minimal reproducible example - 您还没有描述如何重新创建问题并且自动完成代码混淆了问题
  • madalinivascu 我正在使用我的动态输入字段值进行此计算。而不是 A、B、C、D,而是输入字段的值。我刚刚用它来向您展示计算模式。谢谢。
  • 在哪里?什么时候?用户必须做什么才能看到这个计算?你的尝试在哪里?这不只是一个授权问题吗?既然已经有了 jQuery,为什么不使用它呢?
  • 这个计算会在用户点击“计算”按钮时执行。我试着自己解决。但在这方面失败了。希望你能理解。谢谢

标签: javascript jquery html arrays


【解决方案1】:

尝试每个输入循环

 $("#Calculate").click(function(){
        var peVal,roceVal,sgVal,dyVal;
    jQuery(".fields input").each(function (){
        var idHeading=$(this).attr("id");

        if(idHeading=="Your ID for PE input"){
            peVal=parseInt($(this).val());
        }

        if(idHeading=="Your ID for ROCE input "){
            roceVal=parseInt($(this).val());
        }

        if(idHeading=="Your ID for SG input"){
            sgVal=parseInt($(this).val());
        }

        if(idHeading=="Your ID for DY input"){
            dyVal=parseInt($(this).val());
        }

    });
    var output=peVal+roceVal+(2-sgVal)-(4-dyVal/2);
});

【讨论】:

  • 还有问题吗?刚刚修好了。
  • 刚刚修正了错别字。请立即查看。
  • Ravi Patel 感谢您的回答...我只是尝试使用您的回答,但我认为存在一些问题。代码无法正常工作。你能在这里检查一下吗“jsfiddle.net/ywqmo2zu/3
  • @Ravi 值是字符串格式,你需要解析才能做任何计算
  • 非常感谢 Ravi Patel.. 终于得到了正确的答案... 只是因为您的帮助...再次感谢..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
  • 2021-03-27
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多