2016-12-08 10 views
0

我必須使用jquery在相應的文本框(總標題下)的每一行中添加輸入值。我使用jQuery如下。用於輸入輸入的類「值」和用於顯示值的類「值」(前兩列)。使用jQuery在相應文本框的每一行中添加輸入值

jQuery(document).ready(function($) { 
     var $total = $('#total_mark_<?php echo $student['student_code'];?>'), 
      $value = $('.value'); 
      $values = $('.values'); 
     $value.on('input', function(e) { 
      var total = 0; 
      var t=0; 
      $value.each(function(index, elem) { 
       if(!Number.isNaN(parseFloat(this.value, 10))) 
        total = total + parseFloat(this.value, 10); 

      }); 

      $values.each(function(index, elem) { 

        t = t + parseFloat(this.value, 10); 

      }); 

      total=total+t; 
      $total.val(Math.round(total)); 
     }); 
    }); 

當我使用此代碼,我只在最後一個文本框(僅最後一排在總文本框),所有的數值得到一個輸出(:

jQuery的代碼如下所有輸入字段)總結出來,總數只顯示在文本框中。

如何使用jQuery在相應的文本框的每一行中添加輸入值,以在相應的「總計」文本框中顯示輸出?

+0

我們需要看到HTML示例 –

回答

1

我在這裏創建了一個演示,從這個演示可以檢查如何遍歷拋出DOM元素以及如何從中獲取值。

$(document).ready(function() { 
 
    // Traverse throw all rows 
 
    $('.student_marks tbody tr').each(function(){ 
 
     // Get current row 
 
     var student = $(this); 
 
     var total_points = 0; 
 
     $(student).find('.marks').each(function(){ 
 
     total_points+=parseInt($(this).val()); 
 
     }) 
 
     $(student).find('.total').html(total_points); 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> 
 
<div class="container"> 
 
    <table class="table student_marks" > 
 
    <thead> 
 
     <tr> 
 
     <th>Student Name</th> 
 
     <th>Math</th> 
 
     <th>History</th> 
 
     <th>Total</th> 
 
     </tr> 
 
    </thead> 
 
    <tbody> 
 
     <tr> 
 
     <td class="name">John</td> 
 
     <td><input value="50" readonly class="marks"/></td> 
 
     <td><input value="50" readonly class="marks"/></td> 
 
     <td class="total"></td> 
 
     </tr> 
 
     <tr> 
 
     <td class="name">Mac</td> 
 
     <td><input value="60" readonly class="marks"/></td> 
 
     <td><input value="50" readonly class="marks"/></td> 
 
     <td class="total"></td> 
 
     </tr> 
 
     <tr> 
 
     <td class="name">Sena</td> 
 
     <td><input value="40" readonly class="marks"/></td> 
 
     <td><input value="70" readonly class="marks"/></td> 
 
     <td class="total"></td> 
 
     </tr> 
 
     <tr> 
 
     <td class="name">Devy</td> 
 
     <td><input value="80" readonly class="marks"/></td> 
 
     <td><input value="90" readonly class="marks"/></td> 
 
     <td class="total"></td> 
 
     </tr> 
 
     
 
    </tbody> 
 
    </table> 
 
</div>

相關問題