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

157
Vistas
Function returns 0 value even though it has a different number stored in it

I'm trying to return a value from a function so that it is displayed in HTML. It returns 0 on the HTML but it returns the correct input value on the alert message inside the function. Here is the code I have:

<body>
  <p>Number of bags: </p>
  <input type="number" id="numBagInputId">
  <input type="submit" id="numBagSubmitId" onClick="myFunction()">
  <p>You will need: </p> 
  <p id="bags"></p>
  <p>grams.</p>
            
<script>
   function myFunction() {
    let dryAmount = document.getElementById("numBagInputId").value * 921;
    alert (dryAmount);
    return dryAmount;
}
        
    let bagTotal = myFunction();
    document.getElementById("bags").innerHTML = bagTotal;
</script>
</body>
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Since you haven't defined any event listener methods, myFunction() is called first. However, the value 0 is returned because data has not yet been entered into the <input> element. To prevent this, I assigned a value to the value attribute of the <input> element. The event listener method of the <input> element is used to update the value within the program.

const inputElement = document.getElementById('numBagInputId');

function myFunction() {
  let dryAmount = inputElement.value * 921;
  console.log(`Result: ${dryAmount}`)
  return dryAmount;
}

function update(){
  let bagTotal = myFunction();
  document.getElementById("bags").innerHTML = bagTotal + " this is the bag total value";
}

inputElement.addEventListener('input', function(){
  update();
});

update();
<p>Number of bags: </p>

<!-- The value attribute is assigned a default value. -->
<input type="number" id="numBagInputId" value="10">

<input type="submit" id="numBagSubmitId" onClick="myFunction()">
<p>You will need: </p> 
<p id="bags"></p>
<span>grams</span>

about 4 years ago · Juan Pablo Isaza Denunciar

0

update your script as given in ss. https://i.stack.imgur.com/HWBKq.jpg

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