I am using the following code to run a calculation as the user type in a number.
<form action="index.php" method="post" autocomplete="off" data-abide> <input type="text" id="rate" name="rate"> <input type="text" name="supplier_cost" class="value-right" pattern="\d*" value="<?php echo $supplier_cost; ?>" id="decimal" required> <input type="text" name="sterling" id="sterling" class="value-right" disabled> <button type="submit" class="button tiny ebc-theme" name="save"><i class="fa fa-floppy-o" aria-hidden="true"></i> SAVE</button> </form> $(document).ready(function(){ var supplier_id = $('#supplier').val().split(","); var period = "<?php echo $period; ?>"; $.ajax({ url: "fetch_rate.php", method: "POST", data:{supplierID:supplier_id[1], periodID:period}, dataType:"text", success:function(data) { $('#rate').val(data); } }); }); $(document).ready(SterlingCalc); document.getElementById('decimal').addEventListener("keyup", SterlingCalc); var rate = document.getElementById('rate'); var sup_cost = document.getElementById('decimal'); function SterlingCalc(){ document.getElementById('sterling').value = (sup_cost.value / rate.value).toFixed(2) || 0; } How do I add code so that the calulation runs on the page load if both the "rate" and "decimal" fields are already loaded (for example, values are populated by database)?
Thanks,
John
SterlingCalc()toFixed(2) || 0makes no sense, because toFixed(2) returns always a string and is always true. So|| 0is never executed.