jquery - 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 选择器进行计算?
谢谢你,凯文
解决方案
考虑以下。
$(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
可能会更好。这真的取决于你在做什么。
推荐阅读
- asynchronous - Netty Http 客户端分析。如何计算服务器响应时间?
- upgrade - 我正在尝试将 Grails 2.4 升级到 3.3.6 并且无法更改环境:从开发到测试。有人能帮我吗?
- docker - Windows 上的 Docker 构建未能建立新连接 Errno 11001 getaddrinfo failed
- python - 如何保存和重用 keras 模型的所有设置?
- python - 是否有任何 jenkins 插件可供开发人员轻松工作(替代 web2py)
- hibernate - 如何获取和/或设置谓词 CriteriaQuery 的参数?
- regex - 在 url 端匹配重定向,忽略子字符串
- c# - 3 台计算机中有 2 台无法创建应用程序包
- scala - 使用 redirectToLog 的 Spark Launcher 不写入日志
- php - 如何将域文件夹指向子域?