How to program a Celcius drive converter to Kelvin? (HTML, Javascript) this source code did not work, would be K = C + 273

Asked

Viewed 53 times

0

<!doctype html>
<html>
<head>
<script src="myscripts.js"></script>
</head>
<body>
<label for="valor1">Celcius <strong>1</strong>:</label>
<input type="text" name="valor1" id="valor1" />
<label for="res">Kelvin:</label>
      <input type="text" name="res" id="res" />
<input type="button" value="Calcular" class="botao" onClick="calcular(document.calcform.oper.value)"/>
</body>
</html>

javascript function calcular(oper) {
var kelvin = 273;
var valor1 = document.calcform.valor1.value;
var res = valor1 + kelvin;
console.log(res);
  document.calcform.res.value = res;
      }
  • You use document.calcform in Javascript, but in HTML there is no calcform...

  • Thank you very much!

1 answer

0

As hkotsubo mentioned, Document.calcform does not exist. To access an element of your Document, among other strategies, you have the getElementById, thus you access the input and can manipulate the value in any way you want/need in your code.

Another point of this problem is the integer transformation, if you don’t do this before the sum, you add a string (input value) to 273, resulting in for example: '123' + 273 = '123273'

<html> 
  <body>
    <script>
      function calcular() {
        var kelvin = 273;
        var valor1 = document.getElementById('valor1').value;
        var res = parseInt(valor1) + kelvin;
        document.getElementById('res').value = res;
      }   
    </script>
    <label for="valor1">Celcius <strong>1</strong>:</label>
    <input type="text" name="valor1" id="valor1" />
    <label for="res">Kelvin:</label>
    <input type="text" name="res" id="res" />
    <input type="button" value="Calcular" class="botao" onClick="calcular()"/>
  </body>
</html>

Browser other questions tagged

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