Reputation: 213
I need to multiply two values of a and b and display in c. Also I need to display the addition value of c using script. Please check my code below:
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)
}
});
OUTPUT
a b c
1 2 2
2 4 8
By the above script,I can multiply a and b and display in c.But how to add two values of 'c' and display in total text box.Need help
Upvotes: 1
Views: 157
Reputation: 11859
try this:
$(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);
}
Upvotes: 2
Reputation: 1934
try this code:-
$(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 example:- http://jsfiddle.net/c2S5d/21/
Upvotes: 1
Reputation: 781068
Put this in cal
after you update $row.find('.id_a').val()
var total = 0;
$(".id_a").each(function() {
total += parseInt($(this).val(), 10);
});
$(".total").text(total);
Upvotes: 1