Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!