使用jquery在表中自动计算

时间:2017-09-02 06:17:21

标签: javascript jquery html

我的要求:

当数量单元格需要与其他父td值相乘时,我将数量单元格表设为可编辑。并对列值求和。
(即)如果我将数量改为2,那么父行需要乘以2&列获取值添加

当我删除或更改数量时,我完成了所有计算部分,计算值保持不变,如何恢复旧值

这是我的小提琴
Fiddle link



$(document).ready(function(){
  $('.quantity').on('change, keyup',function(){
       var val=$(this).text();
     // To avoid auto inc while pressing arrow keys
         var preVal =$(this).data('prevval');
        <!--  console.log(preVal); -->
      if(preVal && preVal == val){
          return;
      }
      $(this).data('prevval',val);
     //To avoid auto inc while pressing arrow keys //
 if(val =='' ||  isNaN(val) || val < 1){
 return;
 }
      $(this).siblings().each(function(){
          var tbvalue=$(this).text();
          var result= parseInt(tbvalue)*parseInt(val);
          
          $(this).text(result);
      }) 
autoSum();
  });

autoSum();
});
function autoSum(){
      for (var i = 1; i < 8; i++) {
        var sum = 0;
        $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').each(function() {
          sum += parseInt($(this).text()) || 0;
        });
        // set total in last cell of the column
        $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
       // $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
      }
}
&#13;
.total {
  background-color: #000;
  color: #fff;
  font-weight: bold;
}
&#13;
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
  <h2>Table calculation</h2>
  <p>Calculaton</p>            
  <table class="auto_sum table table-hover">
    <thead>
      <tr>
        <th>value1</th>
        <th>value2</th>
        <th>value3</th>
        <th>Quantity</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>10</td>
        <td>5</td>
        <td>4</td>
        <td class="quantity" type="number" contenteditable>1</td>
      </tr>
      <tr>
        <td>8</td>
        <td type>2</td>
        <td>3</td>
        <td class="quantity" type="number" contenteditable>1</td>
      </tr>
      <tr>
        <td>20</td>
        <td>3</td>
        <td>5</td>
        <td class="quantity" type="number"  contenteditable>1</td>
      </tr>
        <tr class="total">
          <td> </td>
          <td> </td>
          <td> </td>
          <td> </td>
        </tr>
    </tbody>
  </table>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

在每一行中,使用存储要乘以的数字的td,将原始数字保存在td中的data-val属性中,并将内容可编辑值乘以该值。将乘积值显示为td文本。这里的一个变化是,当你删除contenteditable cell的值时,它会将它作为1用于行计算,但不会将其视为列乘法。

HTML part
<div class="container">
  <h2>Table calculation</h2>
  <p>Calculaton</p>            
  <table class="auto_sum table table-hover">
    <thead>
      <tr>
        <th>value1</th>
        <th>value2</th>
        <th>value3</th>
        <th>Quantity</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-val="10">10</td>
        <td data-val="5">5</td>
        <td data-val="4">4</td>
        <td class="quantity" type="number" contenteditable>1</td>
      </tr>
      <tr>
        <td data-val="8">8</td>
        <td data-val="2">2</td>
        <td data-val="3">3</td>
        <td class="quantity" type="number" contenteditable>1</td>
      </tr>
      <tr>
        <td data-val="20">20</td>
        <td data-val="3">3</td>
        <td data-val="5">5</td>
        <td class="quantity" type="number"  contenteditable>1</td>
      </tr>
        <tr class="total">
          <td> </td>
          <td> </td>
          <td> </td>
          <td> </td>
        </tr>
    </tbody>
  </table>
</div>

JS Part

$(document).ready(function(){
  $('.quantity').on('change, keyup',function(){
       var val=$(this).text();
     // To avoid auto inc while pressing arrow keys
         var preVal =$(this).data('prevval');

      $(this).data('prevval',val);
     //To avoid auto inc while pressing arrow keys //
 if(val =='' ||  isNaN(val) || val < 1 || val == undefined){
    val = 1;
 }

      $(this).siblings().each(function(){  
          var tbvalue=$(this).data("val");
           var result= parseInt(tbvalue)*parseInt(val);
          $(this).text(result);
      });
autoSum();
  });

autoSum();
});
function autoSum(){
      for (var i = 1; i <= 4; i++) {
        var sum = 0;
        var tdBoxes = $('.auto_sum>tbody>tr>td:nth-child(' + i + ')');
        for(var j=0; j<tdBoxes.length-1;j++)
        {
          var value = $(tdBoxes[j]).text();
          //alert(value);
          sum += (value == undefined || value == "")? 0 : parseInt(value);
        }
        // set total in last cell of the column
        $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
       // $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
      }
}

答案 1 :(得分:1)

所有详细信息都在工作演示中注释。我添加了<form><output><input type='number'><input type='hidden'>。另外,我不记得<td>属性typenumber值。{/ p>

通过组合正确的元素和属性(甚至可能是一些CSS),您不必编写如此多的JS / jQ,因为HTML中构建了表单函数的许多方面。

演示

// Reference the <form>
var main = document.forms.main;

// Reference of all of <input> and <output> of <form>
var field = main.elements;

/* Register the input event on the <form>
|| ANY input event triggered within <form> will...
*/
main.addEventListener('input', function(e) {

  // Check to see which field is the user inputing into
  if (e.target !== e.currentTarget) {
  
    // Reference that field
    var input = document.getElementById(e.target.id);
    // console.log(input.value);
    
    // Get the row of the field
    var row = input.parentNode.parentNode;
    // console.log(row);
    
    /* Gather all hidden fields of that row into a NodeList
    || and convert that NodeList into an array.
    */
    var rowArray = Array.from(row.querySelectorAll('[type=hidden]'));
    // console.log(rowArray);
    
    // On each hidden field, perform the following function...
    rowArray.forEach(function(cel, idx) {
    
      // Get the value of hidden field
      const base = cel.value;
      
      // Find the <output> that comes after the hidden field
      var output = cel.nextElementSibling;
      
      /* Calculate the product of the hidden field's value
      || and the input field's value
      */
      var val = parseInt(base, 10) * parseInt(input.value, 10);
      
      // Display the prouct in the <output>
      output.value = val;
    });
    
    /* Because we registered the input event on the <form>,
    || we have many ways to manipulate the <form>'s fields.
    || In this demo we have been using: 
    || HTMLFormElement and HTMLFormControlsCollection interfaces 
    || https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement
    || http://www.dyn-web.com/tutorials/forms/references.php#dom0
    */
    field.out1.value = Number(field.o1a.value) + Number(field.o1b.value) + Number(field.o1c.value);

    field.out2.value = Number(field.o2a.value) + Number(field.o2b.value) + Number(field.o2c.value);

    field.out3.value = Number(field.o3a.value) + Number(field.o3b.value) + Number(field.o3c.value);

    field.out4.value = Number(field.out1.value) + Number(field.out2.value) + Number(field.out3.value);

  }
});
.total {
  background-color: #000;
  color: #fff;
  font-weight: bold;
}

input,
output {
  display: inline-block;
  font: inherit;
  width: 6ch;
  border: 0;
  text-align: center;
}

.quantity input {
  padding-top: .5em;
  outline: 0;
}
-
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <style>

  </style>
</head>

<body>
  <div class="container">
    <form id='main'>
      <table class="auto_sum table table-hover">
        <thead>
          <caption>
            <h2>Table Calculation</h2>
            <h3>Quanities</h3>
          </caption>
          <tr>
            <th>Value1</th>
            <th>Value2</th>
            <th>Value3</th>
            <th>Quantity</th>
          </tr>
        </thead>
        <tbody>
          <tr id='rowA'>
            <td>
              <!--[0][1]-->
              <input id='v1a' type='hidden' value='10'>
              <output id='o1a'>0</output>
            </td>
            <td>
              <!--[2][3]-->
              <input id='v2a' type='hidden' value='5'>
              <output id='o2a'>0</output>
            </td>
            <td>
              <!--[4][5]-->
              <input id='v3a' type='hidden' value='4'>
              <output id='o3a'>0</output>
            </td>
            <td class="quantity">
              <!--[6]-->
              <input id='qa' type='number' value='0' max='999' min='0'>
            </td>
          </tr>
          <tr id='rowB'>
            <td>
              <!--[7][8]-->
              <input id='v1b' type='hidden' value='8'>
              <output id='o1b'>0</output>
            </td>
            <td>
              <!--[9][10]-->
              <input id='v2b' type='hidden' value='2'>
              <output id='o2b'>0</output>
            </td>
            <td>
              <!--[11][12]-->
              <input id='v3b' type='hidden' value='3'>
              <output id='o3b'>0</output>
            </td>
            <td class="quantity">
              <!--[13]-->
              <input id='qb' type='number' value='0' max='999' min='0'>
            </td>
          </tr>
          <tr id='rowC'>
            <td>
              <!--[14][15]-->
              <input id='v1c' type='hidden' value='20'>
              <output id='o1c'>0</output>
            </td>
            <td>
              <!--[16][17]-->
              <input id='v2c' type='hidden' value='3'>
              <output id='o2c'>0</output>
            </td>
            <td>
              <!--[18][19]-->
              <input id='v3c' type='hidden' value='5'>
              <output id='o3c'>0</output>
            </td>
            <td class="quantity">
              <!--[20]-->
              <input id='qc' type='number' value='0' max='999' min='0'>
            </td>
          </tr>
          <tr class="total">
            <td>
              <!--[21]-->
              <output id='out1' for='o1a o1b o1c'>0</output>
            </td>
            <td>
              <!--[22]-->
              <output id='out2' for='o2a o2b o2c'>0</output>
            </td>
            <td>
              <!--[23]-->
              <output id='out3' for='o3a o3b o3c'>0</output>
            </td>
            <td>
              <!--[24]-->
              <output id='out4' for='out1 out2 out3'>0</output>
            </td>
          </tr>
        </tbody>
      </table>
    </form>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>

</html>