JavaScript Functions

1

You were asked to create a Form to get the value of A, B, and C to stop the calculations of 2nd degree equations and return the discriminant in a tag, but the function is returning NaN. Code below.

            <p>A: <input type = "text" id = "varA" size = "20"></p>
            <p>B: <input type = "text" id = "varB" size = "20"></p>
            <p>C: <input type = "text" id = "varC" size = "20"></p>
            <button onClick = "calcularEqua()">Calcular!!</button>

            <h1 id = "hResult">O resultado sera exibido aqui</h1>

<script>
                function calcularEqua() {
                    var inputA = document.getElementsByTagName("varA");
                    var inputB = document.getElementsByTagName("varB");
                    var inputC = document.getElementsByTagName("varC"); 

                    var a = parseInt(inputA.value);
                    var b = parseInt(inputB.value);
                    var c = parseInt(inputC.value);

                    var res = Math.pow(b,2) - (4 * a * c);

                    document.getElementById('hResult').innerHTML = res;
                }
            </script>
    
asked by anonymous 17.04.2018 / 19:43

1 answer

0

Instead of using the getElementsByTagName() method where you would search the elements for the tag, in the <input> case, use getElementById() . Since this is the argument you are already using for querying the DOM.

function calcularEqua() {
  var inputA = document.getElementById("varA");
  var inputB = document.getElementById("varB");
  var inputC = document.getElementById("varC");

  var a = parseInt(inputA.value);
  var b = parseInt(inputB.value);
  var c = parseInt(inputC.value);

  var res = Math.pow(b, 2) - (4 * a * c);

  document.getElementById('hResult').innerHTML = res;
}
<p>A: <input type="text" id="varA" size="20"></p>
<p>B: <input type="text" id="varB" size="20"></p>
<p>C: <input type="text" id="varC" size="20"></p>
<button onClick="calcularEqua()">Calcular!!</button>

<h1 id="hResult">O resultado sera exibido aqui</h1>
    
10.12.2018 / 15:43