Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
innerHtml of a variable does update but returns back

Even though the function deposit() updates the innerHTML it, unfortunately, returns back the constant variable of bal.

var bal = 100;

var currentBalance = document.getElementById("REPLACED")
currentBalance.innerHTML = "Current balance: " + bal + " Pesos"


function deposit() {
  var moneygiven = parseInt(document.getElementById("balance").value);
  bal += moneygiven
  if (moneygiven > 0) {
    bal += moneygiven
    var output = "Current balance: " + bal + " Pesos";
    // Display result
    currentBalance.innerHTML = "Current balance: " + bal + " Pesos"
  } else {
    alert("Error")
  }

}
<div>
  <p>Code</p>
  <h1 id="REPLACED"></h1>
  <form>
    <input type="number" placeholder="00000" id="balance" name="balanceNumber" />
    <button onclick="deposit()" value="" id="btnDeposit">Deposit</button>
  </form>
</div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The default type for button is submit.

You don't want your button to submit your form when clicked, so change it to type="button".

var bal = 100;

var currentBalance = document.getElementById("REPLACED")
currentBalance.innerHTML = "Current balance: " + bal + " Pesos"


function deposit() {
  var moneygiven = parseInt(document.getElementById("balance").value);
  // bal += moneygiven // not sure if you really want this line of code twice in case of moneygiven > 0
  if (moneygiven > 0) {
    bal += moneygiven
    var output = "Current balance: " + bal + " Pesos";
    // Display result
    currentBalance.textContent = "Current balance: " + bal + " Pesos"
  } else {
    alert("Error")
  }

}
<div>
  <p>Code</p>
  <h1 id="REPLACED"></h1>
  <form>
    <input type="number" placeholder="00000" id="balance" name="balanceNumber" />
    <button onclick="deposit()" value="" id="btnDeposit" type="button">Deposit</button>
  </form>
</div>

Also, there is no need to work with the unsafe innerHTML property here; use textContent whenever you don't need to inject HTML.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!