How to get integer value from textbox and convert to integer? Javascript

0

I'm starting with Js on the technician and I'm trying to get the value of the textbox by document.getElementById and then do operations to return the value by alert but to no avail. Here is the code:

<html>
<head>
    <title></title>
    <meta charset="UTF-8">
    <script language="Javascript">
    var kminicial = parseInt(document.getElementById("1").value);
    var kmfinal = parseInt(document.getElementById("2").value);
    var abast = parseInt(document.getElementById("3").value);
    var dist=kmfinal-kminicial;
    var mediakm=dist/abast;
    function calcula() {
        alert("A distância percorrida é: " + dist + "\n" + "A média de km por litros é:" + mediakm);    
    }
    </script>
</head>
<body>
    <p> Quilometragram Inicial: <input type="text" name="kminicial" id="1"> 
    <p> Quilometragram Final: <input type="text" name="kmfinal" id="2"> 
    <p> Litros Abastecidos: <input type="text" name="abast" id="3"> 
    <br><br><br><input type="button" name="calcula" value="Calcular" onclick="calcula()">
</body>

    
asked by anonymous 01.11.2017 / 13:14

1 answer

1

ids can not have just numbers. You must have at least one letter, as you can see here in the documentation from W3C :

  

and must contain at least one character

In addition, the code like this interprets the value of the fields as soon as it starts:

var kminicial = parseInt(document.getElementById("1").value);

Without the page being loaded or even the user filled in the fields. You should do these readings only in the calcula function.

See the example:

<html>
<head>
    <title></title>
    <meta charset="UTF-8">
    <script language="Javascript">
    
    function calcula() {
      //agora as leituras do html são feitas apenas quando calcula
      var kminicial = parseInt(document.getElementById("c1").value); //agora c1
      var kmfinal = parseInt(document.getElementById("c2").value);
      var abast = parseInt(document.getElementById("c3").value);
      var dist=kmfinal-kminicial;
      var mediakm=dist/abast;
    
      alert("A distância percorrida é: " + dist + "\n" + "A média de km por litros é:" + mediakm);    
    }
    </script>
</head>
<body>
    <p> Quilometragram Inicial: <input type="text" name="kminicial" id="c1"><!--id c1--> 
    <p> Quilometragram Final: <input type="text" name="kmfinal" id="c2"> 
    <p> Litros Abastecidos: <input type="text" name="abast" id="c3"> 
    <br><br><br><input type="button" name="calcula" value="Calcular" onclick="calcula()">  
</body>

Note that to be consistent with the documentation I changed the ids: 1 , 2 , 3 to c1 , c2 , c3 and set their getElementById .     

01.11.2017 / 14:00