Estoy escribiendo una función que debería cambiar el color de una etiqueta h1 según el valor del texto en un campo de formulario de entrada de texto. Mi código HTML y JavaScript está a continuación:
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>Aquí, si escribo el número 0 en mi campo de entrada y presiono Intro (o hago clic en Enviar), el color de la etiqueta h1 no cambia. Sin embargo, verifiqué si el evento se activó o no.
Cuando modifico mi detector de eventos a esto:
let form = document.getElementById('my-form'); form.onsubmit = function() { alert('You submitted the form'); };, la alerta aparece en el navegador. Esto sugiere que hay un problema con mi función checkIfZero() y no vincula necesariamente la función al elemento de formulario.
¿Puedo saber cómo arreglar mi función para que cambie de color al activar el evento de envío? Gracias.