首页 > 解决方案 > jQuery 使用选择器计算多个文本字段

问题描述

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

这是我的表格示例...

    <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 选择器进行计算?

谢谢你,凯文

标签: jqueryjquery-selectors

解决方案


考虑以下。

$(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可能会更好。这真的取决于你在做什么。


推荐阅读