Javascript functions

Asked

Viewed 53 times

1

It was asked to create a form to take the value of A, B and C to stop calculating the equations of 2° degree and return the discriminant in a tag , but the function is returning Nan. Code just 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>
  • Replaces getelementsbytagname with getElementById, because when you call getelementsbytagname you get a collection of tags. Elements By Tag Name https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp Element By ID: https://www.w3schools.com/jsref/met_document_getelementbyid.asp

  • 2

    Try to change document.getElementsByTagName for document.getElementsById

  • Thanks @David, silly mistake, thank you!!

1 answer

1

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

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>

Browser other questions tagged

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