我需要将a和b的两个值相乘并在c中显示。另外我需要使用脚本显示c的加法值。请检查下面的代码:
HTML:
<table border="1" id="table" class="table">
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
<?php
$select= "SELECT * from table where id=1";
$result = mysql_query($select);
$row_count=1;
while($row = mysql_fetch_assoc($result))
{
?>
<tr>
<td><input type="text" value="<?php echo $row['name_a']; ?>" name="name_a[]" class="name_a"></td>
<td><input type="text" value="<?php echo $row['code_a']; ?>" name="code_a[]" class="code_a"></td>
<td><input type="text" name="id_a[]" class="id_a" ></td>
</tr>
<?php
$row_count++;
}
?>
</table>
<input type="text" name="total" class="total">
SCRIPT:
$(document).ready(function() {
$('#table').on('keyup', '.name_a', cal)
.on('keyup', '.code_a', cal)
.on('keyup', '.id_a', cal);
function cal() {
var $row = $(this).closest('tr'),
name_a = $row.find('.name_a').val(),
code_a = $row.find('.code_a').val(),
id_a = $row.find('.id_a').val(),
id_a_calc = name_a * code_a;
$row.find('.id_a').val(id_a_calc)
}
});
输出
a b c
1 2 2
2 4 8
通过上面的脚本,我可以将a和b相乘并显示在c中。但是如何添加两个值&#39; c&#39;并在总文本框中显示。需要帮助
答案 0 :(得分:2)
试试这个:
$(document).ready(function() {
$('#table').on('keyup', '.name_a', cal)
.on('keyup', '.code_a', cal)
.on('keyup', '.id_a', cal);
});
function cal() {
var $row = $(this).closest('tr'),
name_a = $row.find('.name_a').val(),
code_a = $row.find('.code_a').val(),
id_a = $row.find('.id_a').val(),
id_a_calc = name_a * code_a;
$row.find('.id_a').val(id_a_calc);
var total = 0;
$(".id_a").each(function() {
// console.log($(this).val());
if($(this).val().length > 0){
total += parseInt($(this).val(), 10);
}
});
$(".total").val(total);
}
答案 1 :(得分:1)
更新cal
$row.find('.id_a').val()
var total = 0;
$(".id_a").each(function() {
total += parseInt($(this).val(), 10);
});
$(".total").text(total);
答案 2 :(得分:1)
试试这段代码: -
$(document).ready(function() {
$("#btn").click(function() {
var cValue = 0;
$('#table tr td:nth-child(3)').each(function() {
cValue += parseInt($(this).html());
});
$("#total").val(cValue)
});
});
jsfiddle示例: - http://jsfiddle.net/c2S5d/21/