I have a script that calculates the values in some fields in real time at the moment you type the value and it is working fine.
However, if I send the values to a db and then take them back from there and populate the fields from the request from the db the fields are no longer calculated unless they are retyped in the already populated fields.
Any idea how can I do the calculation to fire up at the moment I load the populated form from the db?
This is the Jscript
<script type="text/javascript">
$(document).ready(function() {
$('input[id=r],input[id=p]').change(function(e) {
var total = 0;
var $row = $(this).parent();
var rate = $row.find('input[id=r]').val();
var pack = $row.find('input[id=p]').val();
total = parseFloat(rate * pack);
//update the row total
$row.find('.amount').text(total);
var total_amount = 0;
$('.amount').each(function() {
//Get the value
var am= $(this).text();
console.log(am);
if (typeof console == "undefined") {
this.console = {log: function() {}};
}
//if it's a number add it to the total
if (IsNumeric(am)) {
total_amount += parseFloat(am, 10);
}
});
$('.total_amount').text(total_amount);
});
});
//isNumeric function Stolen from:
//http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
</script>
And this is the HTML
<tr>
<td></td>
<td>
<div>
<input name="a2c" type="text" size="10" value="<? echo "$a2c";?>">
<input id="r" class="rate" name="a2q" type="text" maxlength="255" size="5" value="<? echo "$a2q";?>">
<input id="p" class="pack" name="a2p" type="text" maxlength="255" size="5" value="<? echo "$a2p";?>">
<span class="amount"></span></div>
</td>
</tr>
<tr>
<td></td>
<td>
<div>
<input name="a3c" type="text" size="10" value="<? echo "$a3c";?>">
<input id="r" class="rate" name="a3q" type="text" maxlength="255" size="5" value="<? echo "$a3q";?>">
<input id="p" class="pack" name="a3p" type="text" maxlength="255" size="5" value="<? echo "$a3p";?>">
<span class="amount"></span></div>
</td>
</tr>
What you could do is to also run your function when the script loads.
One way to do this is to remove the anonymous function from the .change(), and give it a name.
Because your function isn’t called when the page is done loading, as you inject your values using PHP. This way your function is also run once when the page is done loading, and thus the values are calculated using your function.
A different way, as you’re already using jQuery, is to force the event to occur:
This is the way explained by MassivePenguin.