Сумма значений из столбца в таблице - PullRequest
0 голосов
/ 20 июня 2020

Я создал веб-сайт с использованием скрипта Google Apps.

На этом веб-сайте у меня есть таблица с 4 столбцами (Товар, Цена, Количество и Итого). Как только вы вводите количество товара, столбец 4 автоматически вычислит общую сумму.

Мне нужно получить сумму всех значений из столбца 4. Которая будет отображаться как «Итого» под таблицей.

Как я могу сделай это? спасибо.

Это мой код:

 

   function sumAll() {
  jQuery.each( $('.total'), function( index, textFeild) {
     var value = parseInt($(textFeild).val()); 
     if(isNaN(value) == false) {
        total = total+ value;
      }   
    });
 }
 
calc_total();

$(".qty").on('input', function(){
  var parent = $(this).closest('tr');
  var price  = parseFloat($('.totals',parent).text());
  var choose = parseFloat($('.qty',parent).val());

  $('.sum',parent).text(choose+price);

  calc_total();
});

function calc_total(){
  var sum = 0;
  $(".totals").each(function(){
    sum += parseFloat($(this).text());
  });
  
  $('#sum').text(sum);
}




const myTable = document.querySelector('#myTableID')

myTable.oninput = e =>
{
  let rowIndex = e.target.parentNode.parentNode.rowIndex
    , Qte      = getInput_N_RowCell(rowIndex,0)
    , Rate     = getInput_N_RowCell(rowIndex,1)

  setInput_RowCell(rowIndex,2, (Qte * Rate) )

  console.log('sum=',  Sum_RowInputValues(rowIndex) )
}

function getInput_N_RowCell(xRow, xCell) {
  return Number(myTable.rows[xRow].cells[xCell].querySelector('input').value) || 0
}

function setInput_RowCell(xRow, xCell, value) {
  myTable.rows[xRow].cells[xCell].querySelector('input').value = value
}


function myFunction() {
var val = Math.floor(1000 + Math.random() * 9000);
document.getElementById("demo").innerHTML =  "Order # " + val;    
}
h1{
  background: -webkit-linear-gradient(#FFC0CB, #FF1493);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
h3{
  text-transform: uppercase; 

  background: -webkit-linear-gradient(#FFC0CB, #FF1493);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
* {
  box-sizing: border-box;
}

.column {
  margin-left:5%;
  float: left;
  width: 20%;
}
.row:after {
  content: "";
  display: table;
  clear: both;
}

h4{
 margin-left: 2%;
 color: #008B8B;
 font-weight: 900;
 text-transform: uppercase;
 
}
h5{
 color: red;
 text-transform: uppercase;
 font-weight: 900;
}

h1{
 color: #FFC0CB;
 text-transform: uppercase;
 font-weight: 900;
}

.button {
  background-color: #FF69B4; /* Green */
  border: none;
  color: white;
  padding: 8px 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 10px;
  margin: 4px 2px;
  cursor: pointer;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 4px #999;
}
.button1:hover {background-color: #FFC0CB}

.button:active {
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}


.button1 {
  margin-left: 3%;
  border-radius: 12px;
  background-color: white; 
  color: black; 
  border: 2px solid #FF69B4;
}

th {
  text-align: center;
}

td {
  text-align: right;
}

th, td {
  border-bottom: 1px solid #ddd;
}

tr:hover {background-color: #f5f5f5;}
<!DOCTYPE html>
<html>

  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  </head>
  
  <body>
  

<h1 style="margin-left:6%;">THE MILK TEA CLUB</h1> <br>

<table id='myTableID0'style="display: inline-block; float: left; font-size: 18px; padding-left: 19px;">
  <thead>
    <tr>
      <th>Item</th>
    </tr>
  </thead>
  <tbody>
    <tr style="background-color: #fff0f8;">
      <td>Classic</td>
    </tr>
    <tr style="background-color: #fff0f8;">
      <td>Wintermelon</td>
    </tr>
    <tr style="background-color: #fff0f8;">
      <td>Chocolate</td>
    </tr>
    <tr style="background-color: #f2f2f2;">
      <td>Classic with Pearl</td>
    </tr>
    <tr style="background-color: #f2f2f2;">
      <td>Wintermelon with Pearl</td>
    </tr>
    <tr style="background-color: #f2f2f2;">
      <td>Chocolate with Pearl</td>
    </tr>
    <tr style="background-color: #fff0f8;">
      <td>Classic with Crystal</td>
    </tr>
    <tr style="background-color: #fff0f8;">
      <td>Wintermelon with Crystal</td>
    </tr>
    <tr style="background-color: #fff0f8;">
      <td>Chocolate with Crystal</td>
    </tr>
    
  </tbody>
</table>

<table id='myTableID'style="display: inline-block; font-size: 15px; padding-left: 5px;">

  <thead>
    <tr>
      <th style='font-size: 18px;'>Rate</th>
      <th style='font-size: 18px;'>Quantity</th>
      <th style='font-size: 18px;'>Total</th>
    </tr>
  </thead>
  <tbody>
      <tr style="background-color: #fff0f8;">
      <td><input id="rate" value='75' size='5' style='text-align:center; font-size: 14px;' disabled></td>
      <td><input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'></td>
      <td><input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled></td>
    </tr>
    <tr style="background-color: #fff0f8;">
      <td><input id="rate" value='75' size='5' style='text-align:center; font-size: 14px;' disabled></td>
      <td><input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'></td>
      <td><input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled></td>
    </tr>
    <tr style="background-color: #fff0f8;">
      <td><input id="rate" value='75' size='5' style='text-align:center; font-size: 14px;' disabled></td>
      <td><input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'></td>
     <td><input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled></td>
    </tr>
    
    <tr style="background-color: #f2f2f2;">
      <td><input id="rate" value='85' size='5' style='text-align:center; font-size: 14px;' disabled></td>
      <td><input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'></td>
      <td><input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled></td>
    </tr>
    <tr style="background-color: #f2f2f2;">
      <td><input id="rate" value='85' size='5' style='text-align:center; font-size: 14px;' disabled></td>
      <td><input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'></td>
      <td><input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled></td>
    </tr>
    <tr style="background-color: #f2f2f2;">
      <td><input id="rate" value='85' size='5' style='text-align:center; font-size: 14px;' disabled></td>
      <td><input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'></td>
      <td><input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled></td>
    </tr>
     
    <tr style="background-color: #fff0f8;">
      <td><input id="rate" value='85' size='5' style='text-align:center; font-size: 14px;' disabled></td>
      <td><input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'></td>
      <td><input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled></td>
    </tr>
    <tr style="background-color: #fff0f8;">
      <td><input id="rate"value='85' size='5' style='text-align:center; font-size: 14px;' disabled></td>
      <td><input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'></td>
      <td><input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled></td>
    </tr>
    <tr style="background-color: #fff0f8;">
      <td><input id="rate" value='85' size='5' style='text-align:center; font-size: 14px;' disabled></td>
      <td><input id="qty" type='text' size='5' style='text-align:center; font-size: 14px;'></td>
      <td><input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled></td>
    </tr>
    
  <tr>
    <th colspan="2" style="text-align:right">Total:</th>
    <th colspan="2" style="text-align:center"><span id="sum"></span></th>
  </tr>
  
  </tbody>
</table><br>

<div class="row">

  <div class="column">
    <h3><b>Order Logs</b></h3>
    <button class="button button1" onclick="myFunction()"> Get Order </button><button class="button button1" onlick="sumAll()"> Record Order </button>
    <h2 id="demo"></h2><!-- ORDER NUMBER -->
    
 </div> 
  
</div>

</body>
</html>

1 Ответ

1 голос
/ 20 июня 2020

Всегда избегайте присвоения одного и того же идентификатора нескольким элементам. Каждому входу итогов можно назначить класс-заполнитель. Например,

<input id='totals' class='total' type='text' size='5' style='text-align:center; font-size: 14px;' readonly disabled>

Затем вы можете l oop через эти входы с общим классом, используя селектор классов jQuery и каждую функцию внутри вашей функции sumAll ().

Обновленный код

jQuery.each( $('.total'), function( index, textFeild) {
   var value = parseInt($(textFeild).val()); 
   if(isNaN(value) == false) {
      total = total+ value;
    }   
});

Всегда проверяйте, является ли значение числом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...