Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
Javascript form onsubmit is not working as expected

Why does the following code not cause foo() to be called?

<script>
    function foo(){
        alert("hi"); 
        return false;
    }; 

    var myForm=document.createElement('FORM'); 
    myForm.method='POST'; 
    myForm.action="http://www.example.com/test.php"; 
    myForm.id="myForm"; 

    myForm.onsubmit="return foo()";

    document.body.appendChild(myForm); 

    document.getElementById("myForm").submit();
</script>

I tried myForm.onsubmit="(e)=>{alert("hi"); e.preventDefault()}"; as well, also not working.

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

The onsubmit should be set to the actual function not a string wrapped in quotes

Consider changing this

myForm.onsubmit="return foo()";

To this

myForm.onsubmit=foo;
about 4 years ago · Santiago Gelvez Relatório

0

The onsubmit function is supposed to be a function, not a string.

If you set it as a string, it won't work properly.


To fix it, simply set it as a function, as below.

myForm.onsubmit = foo;

Make sure to not add parentheses (otherwise you will be calling it, and it won't work).


You can also try the addEventListener function, like so.

myForm.addEventListener("submit", foo);

It does the same thing as onsubmit, but with a different syntax.

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda