简体   繁体   中英

Get total from table input as grand total in jquery

I have a table that makes automatically 2 calculations:

  1. Calculation of numbers of days after the selection of date started and date end from two input date field with calendar, result is stored is field (days)
  2. Multiplication of 3 fields (horse* days* price), result is stored ind field (total). There is a button that when we click on it a new row is added.

How can i calculate the grand total of numbers of days and the grand total of the total to display the results in a row below the table ? And i want to grasp the input values in post so that i store them in table using php.

1- table

 <table class='table'>
<tr>
  <th class='th'>Nbr/horses</th>
  <th class='th'>dateStart</th>
  <th class='th'>dateEnd</th>
  <th class='th'>Nbr/days</th>
  <th class='th'>Price</th>
  <th class='th'>Total</th>
</tr>
<tr>
  <td class='td'><input type='number' min='1' name='horse' class='horse'/></td>
  <td class='td'><input type='date' name='dateStart' class='datepicker dateStart'/></td>
  <td class='td'><input type='date' name='dateEnd' class='datepicker dateEnd'/></td>
  <td class='td days'><input type='text' name='days'/>0</td>
  <td class='td'><input type='number' min='1' name='price' class='price'/></td>
  <td class='td total'> <input type='text' name='total1'/></td>
  <td class='td'><button type='button' class='button'>+</button></td>
</tr>

2- functions

 let update = function(lineNode){
let dateStart = $(lineNode).find('.dateStart').datepicker('getDate');
let dateEnd = $(lineNode).find('.dateEnd').datepicker('getDate');
let days = Math.floor( (dateEnd - dateStart) / (3600*24*1000) );
days = days >= 0 ? days : 0;

$( lineNode ).find('.days').text( days );

let horse = parseInt( $(lineNode).find('.horse').val() );
let price = parseInt( $(lineNode).find('.price').val() );
let total = horse * days * price;

$( lineNode ).find('.total').text( total+' €' );
 }

  // add line after click
  let addRow = function(lineNode){
   let clone = lineNode.cloneNode(true);
   $(clone).insertAfter(lineNode);
   reloadEffects();
   }

  let reloadEffects = function(){
  $('.hasDatepicker').removeClass('hasDatepicker').attr('id', '');

$('.datepicker').datepicker();
$('.horse, .price, .datepicker').change( e => {
  update(e.target.parentNode.parentNode);
});
$('.button').click( e => {
  addRow(e.target.parentNode.parentNode);
});

};

// Start

 reloadEffects();

for the total

var sum = 0;
$(".total").each(function(index,value){
sum = sum + parseFloat($(this).find('input[name="total1"]').val());
});
//Sum in sum variable 
console.log(sum);

Apply the same for days !

Working Fiddle : Fiddle

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