[英]Assign a Value to a HTML Table Cell using JQuery
有一个表显示模型条目,每个字段指定一个唯一的div id,该id组合了关键字和每一行的ID。 当用户在表的输入栏中输入数字时,脚本应该执行以下操作:获取同一行中单元格的位置; 并根据其他单元格的值更改两个预定单元格的值。 直到最后一次更新,测试似乎都是成功的。 我尝试使用.val()、. value和.html(),结果单元格为空白,如果脚本没有错误,则显示为0。 有人可以发布正确的jQuery命令以及它为什么起作用吗? 提前谢谢了。
桌子:
<table id="dt_Positions" class="table table-striped">
<thead>
<tr>
<th class="text-center">Month</th>
<th class="text-center">Owed</th>
<th class="text-center">Bought</th>
<th class="text-center">Total Position</th>
<th class="text-center">Non-Fixed</th>
<th class="text-center">Fixed</th>
<th class="text-center">Fixed Position</th>
<th class="text-center">Proposed</th>
</tr>
</thead>
<tbody>
@if (Model.Forecasts.Any())
{
foreach (var record in Model.Summaries)
{
<tr>
<td id="nmonth@(record.fID)" align="center">@String.Format("{0:d}", @record.Month)</td>
<td id="ntotal@(record.fID)" align="center">@record.NTotal</td>
<td id="nbought@(record.fID)" align="center">@record.NBought</td>
<td id="ntposition@(record.fID)" align="center">@record.NTotalPosition</td>
<td id="nvariable@(record.fID)" align="center">@record.NVariable</td>
<td id="nfixed@(record.fID)" align="center">@record.NFixed</td>
<td id="nfposition@(record.fID)" align="center">@record.NFPosition</td>
<td id="ninput@(record.fID)" align="center"><input class="nInput" type="number" name="quantity" min="1" max="50000"></td>
</tr>
}
}
</tbody>
</table>
剧本:
@section Scripts
{
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script type="text/javascript" language="javascript">
$(function () {
$('[id^=ninput]').keyup(function (e) {
var $id = $(this).attr('id');
var $i = $(this);
var $idNum = $id.slice(6);
var $tp = $('#ntposition' + $idNum);
var $fp = $('#nfposition' + $idNum);
var $nt = $('#ntotal' + $idNum);
var $nh = $('#nbought' + $idNum);
var $f = $('#nfixed' + $idNum);
//The lines below appear to be the hiccup
$tp.val($nh.val() + $i.html() - $nt.val());
$fp.val($nh.val() + $i.html() - $f.val());
debugger;
});
});
</script>
}
编辑:返回“ NaN”的id的示例为:ntotal = 29,nbought = 5,ntposition = -24,nvariable = 3,nfixed = 26,nfposition = -21,所有这些在测试View时似乎都是int,但ntotal ,nbought和nfixed在console.log中显示“ NaN”,并在ninput = 5后导致“ NaN”出现在测试视图中。
$i
是文本框,因此要获取其值,您需要使用$i.val()
。 其他元素是表单元格,因此要获取或设置值,您需要.text()
,而不是.val()
。 但是,您使用id
属性使代码复杂化。 相反,请删除然后使用相对选择器
$('input').keyup(function() { // or $('.nInput').keyup
var i = Number$(this).val());
var cells = $(this).closest('tr').children('td');
var tp = cells.eq(3);
var fp = cells.eq(6);
// Get current cell values as a number
var nt = Number(cells.eq(1).text());
var nh = Number(cells.eq(2).text());
var f = Number(cells.eq(5).text());
// Update totals
tp.text(nh + i - nt);
fp.text(nh + i - f);
});
旁注: var i = $(this).val();
可以为null
但不确定您要如何处理-可能只是使用
var i = $(this).val();
if (!i) {
return; // don't do any calculations
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.