Milosz
Milosz

Reputation: 437

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();

Upvotes: 0

Views: 42

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

I'm not sure I've fully understood what you're asking, but I think you're wondering why the second example works on load?

In that case it's because the function is attached to the change and keyup event of the elements, and then a change event is manually triggered.

Upvotes: 1

Related Questions