【问题标题】:jQuery calculate multiple text fields using a selectorjQuery 使用选择器计算多个文本字段
【发布时间】:2021-07-07 22:02:06
【问题描述】:

在这种情况下,我想使用选择器计算不同的文本字段。

这是我的表单示例...

    <input type="text" name="qtr1-revenue-month-1" id="qtr1-revenue-month-1" class="qtr-revenue editable" value="<?php echo $teamLeadMainForecast['qrt1Month1Revenue']; ?>" />
    <input type="text" name="qtr1-revenue-month-2" id="qtr1-revenue-month-2" class="qtr-revenue editable" value="<?php echo $teamLeadMainForecast['qrt1Month2Revenue']; ?>" />
    <input type="text" name="qtr1-revenue-month-3" id="qtr1-revenue-month-3" class="qtr-revenue editable" value="<?php echo $teamLeadMainForecast['qrt1Month3Revenue']; ?>" />

    <input type="text" name="qtr1-margin-month-1" id="qtr1-margin-month-1"  class="qtr editable margin" onblur="calculateQtrMonth.call(this,event)" value="<?php echo $teamLeadMainForecast['qrt1Month1Margin']; ?>" />
   <input type="text" name="qtr1-margin-month-2" id="qtr1-margin-month-2"  class="qtr editable margin" onblur="calculateQtrMonth.call(this,event)" value="<?php echo $teamLeadMainForecast['qrt1Month2Margin']; ?>" />
    <input type="text" name="qtr1-margin-month-3" id="qtr1-margin-month-3"  class="qtr editable margin" onblur="calculateQtrMonth.call(this,event)" value="<?php echo $teamLeadMainForecast['qrt1Month3Margin']; ?>" />

这就是我想要做的。

当我对 id 为 qtr1-margin-month-1 的文本字段进行更改时,我想让它乘以 qtr1-margin-month-1 和 qtr1-revenue-month-1。

我将如何使用 jquery 选择器进行计算?

谢谢你, 凯文

【问题讨论】:

标签: jquery jquery-selectors


【解决方案1】:

考虑以下内容。

$(function() {
  $("input[id^='qtr1-margin-month']").change(function() {
    var $self = $(this);
    var idNum = $self.attr("id").substr(-1);
    var product = parseInt($self.val()) * parseInt($("#qtr1-revenue-month-" + idNum).val());
    alert(idNum + ": " + product);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="qtr1-revenue-month-1" id="qtr1-revenue-month-1" class="qtr-revenue editable" value="1000" />
<input type="text" name="qtr1-revenue-month-2" id="qtr1-revenue-month-2" class="qtr-revenue editable" value="2000" />
<input type="text" name="qtr1-revenue-month-3" id="qtr1-revenue-month-3" class="qtr-revenue editable" value="3000" />

<input type="text" name="qtr1-margin-month-1" id="qtr1-margin-month-1" class="qtr editable margin" value="10" />
<input type="text" name="qtr1-margin-month-2" id="qtr1-margin-month-2" class="qtr editable margin" value="45" />
<input type="text" name="qtr1-margin-month-3" id="qtr1-margin-month-3" class="qtr editable margin" value="75" />

您可以在此处看到此change 回调将适用于许多文本字段。它将根据 ID 查找相关字段,例如,qtr1-margin-month-1 将查找 qtr1-revenue-month-1

您可以根据需要使用blur 事件,但change 可能会更好。这真的取决于你在做什么。

【讨论】:

    猜你喜欢
    • 2020-07-24
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多