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

168
Views
La función devuelve el valor 0 aunque tiene un número diferente almacenado en ella

Estoy tratando de devolver un valor de una función para que se muestre en HTML. Devuelve 0 en el HTML pero devuelve el valor de entrada correcto en el mensaje de alerta dentro de la función. Aquí está el código que tengo:

 <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 answers
Answer question

0

Como no ha definido ningún método de escucha de eventos, myFunction() se llama primero. Sin embargo, se devuelve el valor 0 porque aún no se han ingresado datos en el elemento <input> . Para evitar esto, asigné un valor al atributo de value del elemento <input> . El método de escucha de eventos del elemento <input> se usa para actualizar el valor dentro del programa.

 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 Report

0

actualice su script como se indica en ss. https://i.stack.imgur.com/HWBKq.jpg

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!