DarkShadowAY
DarkShadowAY

Reputation: 175

How to initialise keyup function on page load

I have the following

$(document).ready(function () {
    //window.onload = LabourPrice;

    //Control Proofing Time and LabourCost
    $('#ArtworkDetail_NoOfProofs').keyup(function () {
        function LabourPrice() {
            var time = "@Model.ArtworkDetail.ProofType.DefaultProofTime".split(':');
            var seconds = (+time[0]) * 60 * 60 + (+time[1]) * 60 + (+time[2]);
            var newSeconds = seconds * $('#ArtworkDetail_NoOfProofs').val();

            var date = new Date(newSeconds * 1000);
            var hh = date.getUTCHours();
            var mm = date.getUTCMinutes();
            var ss = date.getSeconds();

            var hourlyLabour = $('#LabourCostCentrePrice').val();
            hourlyLabour = hourlyLabour.split('£');
            var costPerSecond = hourlyLabour[1] / 3600;
            var calculateCost = costPerSecond * newSeconds;
            //alert("£"+calculateCost.toFixed(2));
            $('#ArtworkDetail_ProofingLabourCost').val("£" + calculateCost.toFixed(2));

            // If building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time
            if (hh > 12) { hh = hh % 12; }
            // Ensure each element has two-digits
            if (hh < 10) { hh = "0" + hh; }
            if (mm < 10) { mm = "0" + mm; }
            if (ss < 10) { ss = "0" + ss; }
            // Format your to HH:MM:SS
            var t = hh + ":" + mm + ":" + ss;
            $('#ArtworkDetail_ProofType_DefaultProofTime').val(t);
        }
        });

});

I would like to call the keyup function on page load in order to run some default value I have within a calculation, as the price initially starts off as empty.

Could I do something like this?

$(document).ready(function () {
   window.onload = LabourPrice;
    ....
  }

Then how would I wrap LabourPrice?

Thanks

EDIT

Added Function Detail as requested

Upvotes: 3

Views: 1329

Answers (2)

Travis Heeter
Travis Heeter

Reputation: 14054

LabourPrice should be outside of the keyup event. As you have it now, LabourPrice only exists within the keyup event, but you want to call it from the keyup event:

$(window).load(function(){
  $('#ArtworkDetail_NoOfProofs').keyup(function () {
    LabourPrice();
  }
}

function LabourPrice(){ ... }

Here's a good source on how window.load is different than document.ready, although this is not your main issue.

Upvotes: 2

Peter Smith
Peter Smith

Reputation: 5550

I believe the window.onload is redundant as that is part of ready and the event needs to be set inside the ready function. Why not try

$(document).ready(function () {
    $('#ArtworkDetail_NoOfProofs').keyup(function () {
    });
    LabourPrice();
}
function LabourPrice() {
}

Assuming that LabourPrice is a function (just seen your edit). This function definition can go outside the ready

Upvotes: 2

Related Questions