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

148
Views
El detector de eventos no llama a la función al disparar

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.

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!