javascript does not take form attributes

2

I'm breaking my head to make my javascript copy to a new variable the values passed by a form in HTML. Could someone give me a light?

My HTML looks 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 looks 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 am I missing?

Thank you.

    
asked by anonymous 04.03.2015 / 03:35

1 answer

3

Your code has some structuring problems, and basically its error is in that section

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

getAttribute takes the value of one of the attributes of your element, not its value. Change .getAttribute('x') to value and everything should work fine. Here is a demo of your reworked 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>
    
04.03.2015 / 03:53