简体   繁体   English

使用JQuery将值分配给HTML表格单元格

[英]Assign a Value to a HTML Table Cell using JQuery

There is a table displaying model entries, with each field designated a unique div id combining a keyword and each row's ID. 有一个表显示模型条目,每个字段指定一个唯一的div id,该id组合了关键字和每一行的ID。 When the user enters a number in the table's input column, a script is supposed to: get the locations of the cells on the same row; 当用户在表的输入栏中输入数字时,脚本应该执行以下操作:获取同一行中单元格的位置; and change the values of two predetermined cells based on the values of the other cells. 并根据其他单元格的值更改两个预定单元格的值。 It seems that tests are successful until the final updating. 直到最后一次更新,测试似乎都是成功的。 I've tried using .val(), .value, and .html(), and the resultant cells go blank, or show 0 if the script is error-free. 我尝试使用.val()、. value和.html(),结果单元格为空白,如果脚本没有错误,则显示为0。 Would someone please post the correct jQuery command and why it works? 有人可以发布正确的jQuery命令以及它为什么起作用吗? Many thanks in advance. 提前谢谢了。

The table: 桌子:

<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>

The script: 剧本:

@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>
}

EDIT: Examples of ids returning "NaN" are: ntotal = 29, nbought = 5, ntposition = -24, nvariable = 3, nfixed = 26, nfposition = -21, with all appearing to be int from testing the View, but ntotal, nbought, and nfixed showing "NaN" in the console.log and resulting in "NaN" appearing in the test View after an ninput = 5. 编辑:返回“ 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 is the textbox, so to get its value you need to use $i.val() . $i是文本框,因此要获取其值,您需要使用$i.val() The other elements are table cells, so to get or set the values you need .text() , not .val() . 其他元素是表单元格,因此要获取或设置值,您需要.text() ,而不是.val() However you over complicating code by using id attributes. 但是,您使用id属性使代码复杂化。 Instead, remove then and use relative selectors 相反,请删除然后使用相对选择器

$('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);

});

Side note: The value of var i = $(this).val(); 旁注: var i = $(this).val(); could be null but not sure how you want to handle this - possibly just use 可以为null但不确定您要如何处理-可能只是使用

var i = $(this).val();
if (!i) {
  return; // don't do any calculations
}

You need to know the difference between val() , text() and html() 您需要知道val()text()html()之间的区别

  • val() is for getting and setting values for form elements, input , select etc. val()用于获取和设置表单元素, inputselect等的值。
  • text() is for getting and setting plain unformatted text for non form elements. text()用于获取和设置非表单元素的纯格式文本。
  • html() is for getting and setting inner Html from a node html()用于从节点获取和设置内部HTML

So what you want is: 所以您想要的是:

$tp.text($nh.text() + $i.val() - $nt.text());
$fp.text($nh.text() + $i.val() - $f.text());

Also be careful as + is both mathematical addition and string concatenation in javascript so you may want to cast your parse the strings to the appropriate number type. 也要小心,因为+是javascript中的数学加法字符串连接,因此您可能需要将字符串解析为适当的数字类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM