Variable return in javascript = Undefined

Asked

Viewed 155 times

2

Here’s the code:

    <script type="text/javascript">
    function Enviar(){
    var tempo = document.getElementById('tempo');
    var veloc = document.getElementById('veloc');

    var distancia = parseInt(tempo) * parseInt(veloc);
    var litros = parseInt(distancia) / 12;

    alert("Tempo gasto de viagem:"+tempo.value+"\nVelocidade média:"+veloc.value+
          "\nDistância percorrida:"+distancia.value+"\nLitros gastos:"+litros.value);
    }
    </script>
</body>

But in the result it says that the variable distances and liters are "Undefined", and should contain the results of multiplication and division.

  • The 'time' and 'veloc' element probably do not contain any value can post HTML as well?

  • <form id="form13"> Time spent traveling:<input type="text" id="time">hours<br> Speed Average:<input type="text" id="veloc">km/h<br> <input type="Submit" onclick="Send();" value="Send"> </form>

1 answer

3


The variables tempo and veloc are elements, not values. So it should be:

var distancia = parseInt(tempo.value) * parseInt(veloc.value);

Already distancia and litros are values, and not elements. So it makes no sense to try to catch the value theirs. The alert should be:

alert("Tempo gasto de viagem:"+tempo.value+"\nVelocidade média:"+veloc.value+
      "\nDistância percorrida:"+distancia+"\nLitros gastos:"+litros);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.