Powell21 Powell21 - 19 days ago 5
Javascript Question

JavaScript Fires too fast. Objects not loaded

I have the below JavaScript running on one of my forms OnLoad event :-

function calcServicePriceTotal() {

var grid = document.getElementById('ProjectServicesGrid');
var ids = grid.control.get_allRecordIds();
var sum = 0.00;
var cellValue;

for (i = 0; i < ids.length; i++) {

var cellValue = grid.control.getCellValue('iss_salesprice', ids[i]);
var number = Number(cellValue.replace(/[^0-9\.]+/g, ""));
sum = sum + number;
}
Xrm.Page.data.entity.attributes.get("ava_tempgrossvalue").setValue(sum);
}


Unfortunately I get the following error :-


"Error:'subGridOnload' is undefined"


I believe that the script is firing before the object has had the time it needs to load so what can I do to slow down the function? There must be some way to overcome this but I am far from a JavaScript expert so I could use some help.

Thanks in advance

Answer
function calcServicePriceTotal() {
    if (document.getElementById("Services")) {
        var grid = document.getElementById("Services").control;
        var ids = grid.get_allRecordIds()
        var sum = 0
        for (i = 0; i < ids.length; i++) {
           var cellValue = grid.getCellValue('iss_salesprice', ids[i]);
           var number = Number(cellValue.replace(/\D/g, ''));
           number = number/100;
           sum = sum + number;
       }
       Xrm.Page.data.entity.attributes.get("iss_value").setValue(sum);
    }
    else {
        setTimeout("calcServicePriceTotal();", 500);
    }
}
Comments