Wasim Ahmad Bangash
Wasim Ahmad Bangash

Reputation: 1

Why does the first part of the code not work correctly while the second part works?

<script type="text/javascript">
// first part
document.getElementById("creditBal")
        .addEventListener("keyup", myFunction);

function myFunction() {
  var x = document.getElementById("creditBal");
  var y = document.getElementById("cashBal");
  var z = document.getElementById("totalBal");

  if(y.value == "") {
     z.value = x.value;
  }
  else {
    var tot = parseInt(x.value) + parseInt(y.value);

    z.value = tot + "";
  }
}

// second part
document.getElementById("cashBal")
        .addEventListener("keyup", myFunction);

function myFunction() {
  var x = document.getElementById("creditBal");
  var y = document.getElementById("cashBal");
  var z = document.getElementById("totalBal");

  if(x.value == "") {
    z.value = y.value;
  }
  else {
    var tot = parseInt(x.value) + parseInt(y.value);

    z.value = tot+"";
  }
}
</script>

Upvotes: 0

Views: 21

Answers (1)

KiraMiller
KiraMiller

Reputation: 179

In the code above, both functions are named the same "myFunction" which is causing ambiguity. Try naming the functions with different names. Even myFunction1 and myFunction2 will work just to distinguish them.

Upvotes: 1

Related Questions