I made a pretty basic input field calculator with jquery, which calculates specific html input fields and prints the total sum into input below.
It works like it supposed when jquery events: keyup, change etc. is called. However, there is sometimes a situation when I need to set the input field values from a SESSION or POST variable
Like this:
echo "<div class='calculate_data' data-amount='". $x[$i] ."'>". $y[$i] ."</div>";
echo "<input class='calculate_input' name='input_".$i."' type='text' value='". @$_POST['input_'.$i]."' />";
echo "<input id='total' type='text' disabled='disabled' />";
and then calculator should calculate these values on page load. I’ve tried almost every event, but the script just won’t calculate:
$(document).ready(function() {
$('.calculate_input').bind("click mouseover keyup change focus load on ready", function() {
var sum = 0;
//Sum up
$('.calculate_input').each(function() {
sum += Number($(this).val() * $(this).prev('.calculate_data').attr('data-amount'));
}
//Set the sum of all the previous fields to the #total field
$('#total').val(sum);
if($('#total').val() == "NaN"){
$('#total').val("-");
}
});
});
What jQuery event method does the task or have I done something wrong?
You do not need to use so many event types. You only need it on page load and change. jQuery already should run on page load, so just trigger it outside of the statement.
UPDATE
Changed according to your jQuery change