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

149
Visualizações
Event Listener Not Calling Function Upon Firing

I am writing a function that should change the color of an h1 tag based on the value of the text in a text input form field. My HTML and JavaScript code is below:

function checkIfZero() {
    //Get relevant elements from dom.
    let value = parseInt(document.getElementById('text-field'));
    let heading = document.getElementById('heading');

    //Check if the element is zero, if so, adjust the color of the H1
    if (value === 0) {
        heading.style.color = 'green';
    } else {
        heading.style.color = 'red';
    }
}

//Bind the function to onsubmit.
let form = document.getElementById('my-form');
form.onsubmit = function() {
    checkIfZero();
};
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script src='throwaway.js' type='text/javascript' defer></script>

    <h1 id='heading'>This is a heading</h1>

    <form id='my-form'>
        <input type='text' id='text-field'>
        <input type='submit' id='submit'>
    </form>
</body>

</html>

Here, if I type in the number 0 in my input field and press enter (or click Submit), the color of the h1 tag does not change. However, I did check if the event was triggered or not.

When I amend my event listener to this:

let form = document.getElementById('my-form');
form.onsubmit = function() {
    alert('You submitted the form');
};

, the alert does pop up in the browser. This suggests that there is an issue with my checkIfZero() function and not necessarily binding the function to the form element.

May I know how to fix my function so that it does change color upon firing the submit event? Thank you.

about 4 years ago · Santiago Trujillo
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