Mi requisito:

Tengo una tabla con celda de cantidad como editable cuando se cambia la cantidad, se debe multiplicar con otro valor td principal y sumar los valores de columna.
(es decir) si cambio la cantidad a 2, las filas principales deben multiplicarse por 2 y las columnas obtienen valor agregado

Hice toda la parte del cálculo, lo único cuando elimino o cambio la cantidad, el valor calculado sigue siendo el mismo, cómo volver a los valores anteriores

Aquí está mi violín
Vínculo de Fiddle

$(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');
      }
}
.total {
  background-color: #000;
  color: #fff;
  font-weight: bold;
}
 <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>
0
Harish Karthick 2 sep. 2017 a las 09:17

2 respuestas

La mejor respuesta

Dentro de cada fila, con el td que almacena los números que se van a multiplicar, mantenga los números originales en un atributo data-val en el td y multiplique el valor editable de su contenido con eso. Muestra el valor multiplicado como el texto td. Un cambio aquí es que, cuando elimina el valor de la celda contenteditable, lo toma como 1 para el cálculo de filas, pero no lo considera para la multiplicación de columnas.

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
Amit 2 sep. 2017 a las 06:56

Todos los detalles se comentan en la demostración funcional. Agregué <form>, <output>, <input type='number'> y <input type='hidden'>. Además, no recuerdo que <td> tenga un atributo type o un valor de number tampoco.

Con la combinación de los elementos y atributos correctos (y tal vez incluso un poco de CSS), no tiene que escribir tanto JS / jQ porque hay muchos aspectos de las funciones de formulario integradas en HTML.

Demo

// 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>
1
zer00ne 2 sep. 2017 a las 17:14