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

188
Vistas
Javascript - use the return number of a function to calculate the total

I have separated my form in different functions and although each one works, I can't find a way to use the value returned in the total function.

function adult() {
  let a = document.getElementById("adulte").value;
  let t = a * 100
  document.getElementById("asub").innerHTML = t
  //document.getElementById("sub-a").value = t;
  console.log(t);
  document.getElementById("tprice").innerHTML = a;
  return t;
}

function total() {
  let a = adult();
  document.getElementById("tprice").innerHTML = a;
  console.log(a);
}
<input id="adulte" name="adulte" style="width: 40px" onchange="adult();" />
<span id="aprice"> 100</span>$/nuit
<p> Hébergements pour les adultes = <span id="asub">100</span>$</p>

<button id="total" name="total" onclick="total();">calculate</button>
<span id="tprice"> 50</span>$

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think the following code should work, but I recommend to use form tag..

You don't want trigger adult() every time on input change, which I feel is unnecessary and redundant. still there is a lot of room for code optimization, but I don't want to spoil your method of doing things.

Also in html5, onchange event triggered on two conditions :

1.on Enter Key Press
2.on loosing focus (on blur)

<html>

<head>
  <script>
    function adult(input) {
      let a = input;
      document.getElementById('asub').innerHTML = a * 100;
      document.getElementById('tprice').innerHTML = a;
      return t;
  }

  function total(event) {
    let a = adult(event.target.value);
    document.getElementById('tprice').innerHTML = a;
  }
  </script>
</head>

<body>
  <input type="number" id="adulte" name="adulte" style="width: 40px" onchange="total(event)" min=0 />
  <span id="aprice"> 100</span>$/unit
  <p>Hébergements pour les adultes = <span id="asub">100</span>$</p>

  <button id="total" name="total" onclick="total();">calculate</button>
  <span id="tprice"></span>
</body>

</html>

Added Stackblitz code: click here

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