Add two numbers using Javascript on the onload event

advertisements

How can i add two numbers from text box when the page loads? it only works when i try to create a button for adding.

function sum() {
  var txtFirstNumberValue = document.getElementById('totalprice').value;
  var txtSecondNumberValue = document.getElementById('price1').value;
  var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
  if (!isNaN(result)) {
    document.getElementById('totalprices').value = result;
  }
}

use window.onload

<script>
  function sum() {
            var txtFirstNumberValue = document.getElementById('totalprice').value;
            var txtSecondNumberValue = document.getElementById('price1').value;
            var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
            if (!isNaN(result)) {
                document.getElementById('totalprices').value = result;
            }
        }
  window.onload=sum;
</script>