简体   繁体   中英

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. 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. Would someone please post the correct jQuery command and why it works? 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.

$i is the textbox, so to get its value you need to use $i.val() . The other elements are table cells, so to get or set the values you need .text() , not .val() . However you over complicating code by using id attributes. 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(); could be null but not sure how you want to handle this - possibly just use

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

You need to know the difference between val() , text() and html()

  • val() is for getting and setting values for form elements, input , select etc.
  • text() is for getting and setting plain unformatted text for non form elements.
  • html() is for getting and setting inner Html from a node

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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