How to get whole value of textbox and convert to whole? Javascript

Asked

Viewed 83 times

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 without success. Follows 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>

  • 1

    Declare all variables within the function, which will probably work.

1 answer

1


The ids cannot only have numbers. It must have at least one letter, as you can see here in the W3C documentation:

and must contain at least one Character

In addition, the code as it is interprets the value of the fields at first, when it does:

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

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

Take 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 switched ids: 1,2,3 for c1,c2,c3 and adjusted their getElementById.

Browser other questions tagged

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