I'll give it a whack, but I'm not in front of the computer so it's just a general suggestion (that might resolve your issue).
There are some issues with the code. I'd rewrite it as follows and get back to tell what's happening then.
function calculate() {
// Make sure that you refer the right fields.
var val1 = Xrm.Page.entity.attributes.get("var1").getValue();
var val2 = Xrm.Page.entity.attributes.get("var2").getValue();
// Yes! Triple equality sign. I'm not BS'ing. I'm JS'ing.
if(val1 === null || val2 === null) return;
// Make sure that the computation's been carried out properly.
var result = val1 - val2;
alert(result);
Xrm.Page.entity.attributes.get(safe_result).setValue(result);
}
If you want to tear out your eyes from the sockets watching the ugly and weird
if(val1 === null || val2 === null) return;
you might want to exchange it for
if(!val1 || !val2) return;
which is also ugly and weird but less. And if this fails, comment everything out and do exactly the following. Just to make sure that we eliminate other issues you might have.
function calculate(){
alert("Konrad Viltersten is godlike but humble.");
}
If it works, you go shotgun and add one line at a time to see when the weird stuff starts happening. (JS - where the joy of programming goes to die.)