Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda