Why can’t I call a function by input type="Submit"?

Asked

Viewed 41 times

-2

Hello, I’m having the following problem: when do I use the input type="submit", the form validates the data but does not execute the function, already when I use the input type="button", it normally calls the function.

Why does this happen? Am I calling the function wrong? Follow the code

function calcular() {
  var nome = document.getElementById('userName');
  var peso = document.getElementById('peso');
  var altura = document.getElementById('altura');
  var imcAtual = document.getElementById('imcAtual');
  var imcIdeal = document.getElementById('imcIdeal');
  var pesoIdeal = document.getElementById('pesoIdeal');
  var perder = document.getElementById('perder');
  var res = document.getElementById('resultado');

  Number(peso.value);
  Number(altura.value);
  var imcAt = peso.value / ((altura.value / 100) * (altura.value / 100));


  document.getElementById('resultScreen').style.display = 'block';
  var sau = document.getElementById('saudacoes');
  sau.innerHTML = `Hola, ${nome.value}!`;
  imcAtual.innerHTML = `Seu IMC atual é de ${imcAt.toFixed(2)}`;
  if (imcAt < 18.5) {
    res.innerHTML = 'Você está abaixo do peso';
  } else if (imcAt < 24.9) {
    res.innerHTML = 'Você está com o peso normal :D';
  } else if (imcAt < 29.9) {
    res.innerHTML = 'Você está com sobrepeso';
  } else if (imcAt < 34.9) {
    res.innerHTML = 'Você está com obesidade grau 1';
  } else if (imcAt < 39.9) {
    res.innerHTML = 'Você está com obesidade grau 2';
  }
  imcIdeal.innerHTML = `O IMC Ideal é entre 18,5 e 24,9`;
}
<div id='screen'>

  <form>
    <fieldset id="dados-usuario">
      <input type="text" required name="userName" id="userName" placeholder="Digite seu nome" />
      <input type="number" required min="1" max="250" name="peso" id="peso" placeholder="Digite seu peso" />
      <input type="number" required min="1" max="250" name="altura" id="altura" placeholder="digite sua altura sem vírgulas" />
    </fieldset>
    <fieldset>
      <input type="submit" name="enviar" id="enviar" value="Calcular IMC" onclick="calcular()">
    </fieldset>
  </form>

  <div id="resultScreen">
    <p id="saudacoes"></p>
    <p id="imcAtual"></p>
    <p id="resultado"></p>
    <p id="imcIdeal"></p>
    <p>Peso ideal segundo o seu sexo e altura</p>
    <img src="peso.jpg" id="imgPeso">
  </div>
</div>

  • submit serve to submit the form. If you do not want this to happen, do not use it. Of course use onsubmit and preventDefault, as already indicated, "works", but this seems to me an outline for a problem that would not exist if you used the correct type (in this case, button). So instead of going around, prefer to use the right thing for each function. If you don’t want to submit the form, use the button, that as you yourself have already realized, works properly without need of artifices.

2 answers

3

Use the button=submit same. However, you cannot call the function on the button, because the function in this scenario is to submit the form. Then intercept the form submission with the "onsubmit property".

Example:

<form onsubmit="calcular(event)">
  Enter name: <input type="text">
  <input type="submit">
</form>

Then capture the form submission event, and prevent it from submitting, and then it should just call its function.

function calcular(e) {
  e.preventDefault();
  /* Restante da sua função */
  return false;
}

The e.preventDefault(); prevents form being submitted (page update). I hope to have been clear, feel free to ask.

  • It worked, the problem was just the lack of e.preventDefault(). It saved my life, I was 3 days having this problem :D Thank you.

1

Just by complementing the @fweydson response, you can keep your code as is, just add the code to prevent the form from being submitted as demonstrated in the other reply by adding the event.preventDefault() for the event onsubmit:

<form onsubmit="event.preventDefault()">

See below your code working with the code snippet above added to form:

function calcular() {
  var nome = document.getElementById('userName');
  var peso = document.getElementById('peso');
  var altura = document.getElementById('altura');
  var imcAtual = document.getElementById('imcAtual');
  var imcIdeal = document.getElementById('imcIdeal');
  var pesoIdeal = document.getElementById('pesoIdeal');
  var perder = document.getElementById('perder');
  var res = document.getElementById('resultado');

  Number(peso.value);
  Number(altura.value);
  var imcAt = peso.value / ((altura.value / 100) * (altura.value / 100));


  document.getElementById('resultScreen').style.display = 'block';
  var sau = document.getElementById('saudacoes');
  sau.innerHTML = `Hola, ${nome.value}!`;
  imcAtual.innerHTML = `Seu IMC atual é de ${imcAt.toFixed(2)}`;
  if (imcAt < 18.5) {
    res.innerHTML = 'Você está abaixo do peso';
  } else if (imcAt < 24.9) {
    res.innerHTML = 'Você está com o peso normal :D';
  } else if (imcAt < 29.9) {
    res.innerHTML = 'Você está com sobrepeso';
  } else if (imcAt < 34.9) {
    res.innerHTML = 'Você está com obesidade grau 1';
  } else if (imcAt < 39.9) {
    res.innerHTML = 'Você está com obesidade grau 2';
  }
  imcIdeal.innerHTML = `O IMC Ideal é entre 18,5 e 24,9`;
}
<div id='screen'>

  <form onsubmit="event.preventDefault()"> <!-- Adicionado aqui -->
    <fieldset id="dados-usuario">
      <input type="text" required name="userName" id="userName" placeholder="Digite seu nome" />
      <input type="number" required min="1" max="250" name="peso" id="peso" placeholder="Digite seu peso" />
      <input type="number" required min="1" max="250" name="altura" id="altura" placeholder="digite sua altura sem vírgulas" />
    </fieldset>
    <fieldset>
      <input type="submit" name="enviar" id="enviar" value="Calcular IMC" onclick="calcular()">
    </fieldset>
  </form>

  <div id="resultScreen">
    <p id="saudacoes"></p>
    <p id="imcAtual"></p>
    <p id="resultado"></p>
    <p id="imcIdeal"></p>
    <p>Peso ideal segundo o seu sexo e altura</p>
    <img src="peso.jpg" id="imgPeso">
  </div>
</div>

  • It worked, I just added onsubmit even, you saved my ass!!

Browser other questions tagged

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