使用Jquery或JS在html表中查找列的总和

时间:2018-05-07 17:25:29

标签: javascript jquery html

我有一个使用jQuery创建的html表:

success: function(data, textStatus, errorThrown) {
    var rows ="";

    function formatItem(data) {
        return '<td>'+data.name + '</td> <td> ' + data.price + ' </td><td>' + "<input></input>" +'</td>';
    }

    $.each(data, function (key, item) {
        $('<tr>', { html: formatItem(item) }).appendTo($("#foodnames"));
    });
}

这就是界面的样子:

this is what interface looks like

该表工作正常,所有数据显示。 问题是找到第三列的总和。在哪里我可以输入一个数字并使用id显示它。

无论如何都要这样做?

3 个答案:

答案 0 :(得分:1)

你想要做的是使用jQuery来选择表格,以及每一行的所有第三个td,然后对它求和。基本的伪代码是:

Clear the output box.
ForEach TR
   Select the third TD
   Add that value to the output box.
End ForEach

要在jQuery中执行此操作,您只需要知道如何选择正确的值。分配相关的类/ ID名称很有帮助。

我整理了一个你可以运行的基本示例。当您更改值时,它将动态地将第三列的总和制成表格。我对价格列进行了硬编码,但您可以轻松地输入其他值或输入。

我把它放在一个onChange事件处理程序中,但是如果你从服务器或其他东西加载数据,你可以在onLoad文件或者你的ajax完成时做文件。

&#13;
&#13;
//trigger an event when the input receives a change
$("#exampleTableContainer table td input").off("change").on("change", function(ele) {
  //clear the out put box
  $("#totalOut").val("0");
  //for the table container, select all tr's within the table's tbody. 
  //Excluding tbody will also select the thead.
  $("#exampleTableContainer table tbody tr").each(function(index, rowElement) {
    //tablulate the cost of the current row
    var rowCost = parseInt($(rowElement).find(".cost").text()) * parseInt($(rowElement).find(".amount input").val());
    //if the rowCost is a valid number, add it to whatever is in the output box
    if (rowCost) $("#totalOut").val(parseInt($("#totalOut").val()) + rowCost)
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="exampleTableContainer">
  <table>
    <thead>
      <tr>
        <th class="item">Item</th>
        <th class="cost">Cost</th>
        <th class="amount">Amount</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="item">Item 1</td>
        <td class="cost">123</td>
        <td class="amount">
          <input type="number">
        </td>
      </tr>
      <tr>
        <td class="item">Item 2</td>
        <td class="cost">1</td>
        <td class="amount">
          <input type="number">
        </td>
      </tr>
      <tr>
        <td class="item">Item 3</td>
        <td class="cost">2</td>
        <td class="amount">
          <input type="number">
        </td>
      </tr>
      <tr>
        <td class="item">Item 4</td>
        <td class="cost">4</td>
        <td class="amount">
          <input type="number">
        </td>
      </tr>
    </tbody>
  </table>
  <br>
  <div>
    Total:
    <input id="totalOut" readonly value="0">
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我不确定你是否打算在生产环境中使用它,所以也许这对你想要完成的事情来说太过分了,但我建议使用绑定到表格的基础数据模型。然后你可以从你的数据中得到你的总和:

L2_loss = tf.mulpiply(lamda_param, L2_lst)
loss = tf.add(loss1, L2_loss)

您可以使用这些数据来构建表格:

const data = [
    {food: "Veggie burger", price: 200, qty:1},
    // ...Add as many food items as you like
]

然后,您可以根据数据计算总和,而不是UI:

// Get a reference to the table and create a document fragment
const table = document.getElementById("table-body");
const body = document.createDocumentFragment();

// Fill the fragment with your data:
data.map((value, key) => {
  // Row-building logic goes here
  // this probably isn't what you actually do here:
  const row = document.createElement("tr");
  row.className = key;

  for (let x in value) {
    const dataCell = document.createElement("td");
    dataCell.className = x;
    dataCell.innerHTML = value[x];
    row.appendChild(dataCell);
  }

  body.appendChild(row);
});

table.innerHTML = "";
table.appendChild(body);

您将在表(父节点)上设置事件侦听器并使用event.target查找行和列(在本例中为.qty)并在输入时更新数据对象中的相应字段(qty)改变。

const subTotal = data
  .map((value) => value.price * value.qty)
  .reduce((a, b) => a + b);

document.getElementById("total").textContent = subTotal;

此模式还可以轻松地将更新的数据发送回REST API,以便以后更新数据库。

https://jsfiddle.net/79et1gkc/

我知道你说你正在使用jQuery,但我认为ES6更好。

答案 2 :(得分:-2)

试试这个:

 $(document).ready(function(){
    var total = 0;
    $("#submit").click(function(){

       $(".user_input").each(function(){
          var value = parseInt($(this).val());
          total += value;

       });
       $("#output").text(total);
    });
});

HTML

<input type="text" name="value1" class="user_input"/>
<input type="text" name="value2" class="user_input"/>
<input type="text" name="value3" class="user_input"/>
<button name="submit" id="submit" value="calculate">
Calculate
</button>
<div>
<span>Total:</span><div id="output">

</div>