javascript does not take form attributes

Asked

Viewed 301 times

2

I’m cracking my head to make my javascript copy to a new variable the values passed by a form in HTML. Someone could give me a light?

My HTML is like this:

<div class="imc"><!--primeiro container-->
            <section class="container">
       <h3>Calculadora de Índice de Massa Corporal (IMC).</h3>
                <form id="formIMC" onsubmit="calculaImc()">
                <!--<form id="formIMC">-->
                    <label>
                    Altura:
          <input type="text" id="altura" name="altura" maxlenght="5" size="5" autocomplete="off" required>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    Peso (kg):
                            <input type="text" id="peso" name="peso" maxlenght="5" size="5" autocomplete="off" required>
           </label>
                    <br></br>
                    <!--<button id="calcID" onsubmit="calculaImc()">Calcular</button>-->
                    <input type="submit" value="Calcular">
                </form>
   </section><!--Fim do container-->
        </div>

And my javascript is like this:

function calculaImc() {
    var alturaJS = document.getElementById("altura").getAttribute('altura');
    var pesoJS = document.getElementById("peso").getAttribute('peso');
    alert (alturaJS + " " + pesoJS);
};

However, my Alert only returns "null null". Does anyone know what’s going on? Or rather, what I’m missing?

Grateful.

1 answer

3


Your code has some structuring problems, and basically your error is in this excerpt

var alturaJS = document.getElementById("altura").getAttribute('altura');
var pesoJS = document.getElementById("peso").getAttribute('peso');

The function getAttribute takes the value of one of the attributes of its element, not its value. Change the .getAttribute('x') for value and everything should go well. See below a demonstration of your redone and working code:

document.forms['formIMC'].onsubmit = function() {
  var alturaJS = document.getElementById('altura').value;
  var pesoJS = document.getElementById('peso').value;
  alert(alturaJS + " " + pesoJS);
}
<div class="imc">
  <!--primeiro container-->
  <section class="container">
    <h3>Calculadora de Índice de Massa Corporal (IMC).</h3>
    <form id="formIMC">
      <label for="altura">Altura:</label>
      <input type="text" id="altura" name="altura" maxlenght="5" size="5" autocomplete="off" required>

      <label for="peso">Peso (kg):</label>
      <input type="text" id="peso" name="peso" maxlenght="5" size="5" autocomplete="off" required>
      <br></br>

      <input type="submit" value="Calcular">
    </form>
  </section>
  <!--Fim do container-->
</div>

Browser other questions tagged

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