我有一个表填充了来自页面的C#Model的一定数量的TextBoxFor输入。这些输入的每一列都有一个不同的类名。在任何一个类上使用.change事件,更改的单元格的行和单元格/列号用于标识其正下方行中的单元格。但是,更改的单元格的值始终显示为未定义。我已经尝试搜索SO以获取答案,.val(),. html(),. text(),获取更改的单元格的ID并将.val()应用于此,但是对未更改的单元格的任何引用都是未定义的。如何正确处理已更改的单元格?非常感谢提前!
jQuery的:
$('.firstClass, .secondClass, .thirdClass, .fourthClass, .fifthClass').change(function () {
var $changedCell = $(this);
var $changedRow = $changedCell.parent().index();
var $cellIndex = $changedCell.index();
var $nextRow = $changedRow + 1;
var $table = $('#dt_myTable tr');
var $beneathCell = $table.eq($nextRow).find('td').eq($cellIndex);
var $changedValue = Number($changedCell.val());//Zero or Undefined, depending on using .val() or .html()/.text()!
$beneathCell.text($changedValue);
});
以下是该表的示例:
<table id="dt_myTable" class="table table-bordered">
<thead>
<tr><th class="text-center">Suggested</th><th class="text-center">First</th><th class="text-center">Second</th><th class="text-center">Third</th><th class="text-center">Fourth</th><th class="text-center">Fifth</th></tr>
</thead>
<tbody>
<tr>
<td align="center">Primary</td>
<td class="firstClass" align="center">@Html.TextBoxFor(m => m.FirstPrimary, new { @class = "form-control", data_parsley_required = "true" })</td>
<td class="secondClass" align="center">@Html.TextBoxFor(m => m.SecondPrimary, new { @class = "form-control", data_parsley_required = "true" })</td>
<td class="thirdClass" align="center">@Html.TextBoxFor(m => m.ThirdPrimary, new { @class = "form-control", data_parsley_required = "true" })</td>
<td class="fourthClass" align="center">@Html.TextBoxFor(m => m.FourthPrimary, new { @class = "form-control", data_parsley_required = "true" })</td>
<td class="fifthClass" align="center">@Html.TextBoxFor(m => m.FifthPrimary, new { @class = "form-control", data_parsley_required = "true" })</td>
</tr>
<tr>
<td align="center"><b>Result</b></td>
<td class="firstClass" align="center"></td>
<td class="secondClass" align="center"></td>
<td class="thirdClass" align="center"></td>
<td class="fourthClass" align="center"></td>
<td class="fifthClass" align="center"></td>
</tr>
</tbody>
</table>
答案 0 :(得分:0)
你试图捕捉细胞变化,但你应该抓住文本框的变化。
尝试这样的事情。
$('.firstClass input, .secondClass input, .thirdClass input, .fourthClass input, .fifthClass input').change(function () {
var $changedInput = $(this);
var $changedCell = $changedInput.parent();
var $changedRow = $changedCell.parent().index();
var $cellIndex = $changedCell.index();
var $nextRow = $changedRow + 1;
var $table = $('#dt_myTable tr');
var $beneathCell = $table.eq($nextRow).find('td').eq($cellIndex);
var $changedValue = Number($changedInput.val());//Undefined!
$beneathCell.text($changedValue);
});