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.