Calculationg field values on page load in Jquery
I am trying to learn jquery making simple applications for my website
based on examples found on the Internet. It's a simple multiplication of 3
fields with a result showing in the forth input field. In html the 3
fields have pre-set values.
Question: What makes the result value being calculated on page load
without triggering it with keyup events. I found two approaches and only
the second one calculates value on page load.
$(':input').bind('keypress keydown keyup change',function(){
var qt = parseFloat($('#qt').val(),10),
a = parseFloat($('#a').val(),10),
b = parseFloat($('#b').val(),10);
// var v = '';
if (a && b && qt){
v = a*b*qt;
$('#ans').val(Math.round(a*b*qt*100)/100);
}
// $('#ans').val(v.toString());
});
Second example that works even on page load:
var calcpvc = function() {
var qt = parseFloat($('#qt').val(),10),
a = parseFloat($('#a').val(),10),
b = parseFloat($('#b').val(),10);
//var v = '';
if (a && b && qt){
v = a*b*qt;
$('#ans').val(Math.round(a*b*qt*100)/100);
}
// $('#ans').val(v.toString());
};
$(':input').keyup(calcpvc).change(calcpvc).change();
No comments:
Post a Comment