首页 > 解决方案 > 如何将值计算到一个输入字段中?

问题描述

我有两个 td 值的表

  <td><?php echo $row['remun'];?></td>
  <td><?php echo $row['lum'];?></td>

它根据行值返回一些值

for example
Ist column   2nd column
100              150
200              150
300              150

<input type="text" name="grand_total" id="grand_total" />

javascript

   <script>    
  $('#dynamic-table tr').each(function() {
   if (!this.rowIndex) return; // skip first row
   var customerId = this.cells[4].innerHTML;
   alert(customerId);
  $("#grand_total").val(customerId);
 });

我只得到第一行的值,但我想要所有字段的总和。

标签: phphtmlcodeigniter-3

解决方案


但是你可以很容易地从你的 php 循环中管理它。当然,您正在使用 for 循环来打印表中的记录。

<?php 
   $grand_total=0;          
  foreach($a as $row){ 
  $grand_total=$grand_total+$row['remun']+$row['lum'];
   ?>
 <td class="remun"><?php echo $row['remun'];?></td>
 <td class="lum"><?php echo $row['lum'];?></td>
 <?php }?>
 <td class="total"><?php echo $grand_total;?></td>

但是如果你想用 js 来做,那么请按照下面的操作一次。请在下面添加一些类。

 <td class="remun"><?php echo $row['remun'];?></td>
 <td class="lum"><?php echo $row['lum'];?></td>

现在用户在 jquery 代码下方获取两者的总和。

var t1=0;
var t2=0;
var t3=0;
$('.remun').each(function(){
 t1=t1+parseInt($(this).html());
});
$('.lum').each(function(){
 t2=t2+parseInt($(this).html());
});
t3=t1+t2;
alert(t3);

推荐阅读