[英]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.