Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
Reset Date input using Javascript - Why using declared variable doesn't work?

So I'm trying to reset a date if the input date is today or in the past, just wondering why doesn't date = "" work since I already declared the variable "date" earlier, but I found that it works if I type document.getElementById("date").value = ""; instead, when (I presume) they're the same thing?

function validate_date() {
    // convert to Date objects to compare
    var date = document.getElementById("date").value;
    var date_object = new Date(date)
    var today = new Date();

    if (date_object <= today) {
        alert("Date cannot be today or the past!");
        // document.getElementById("date").value = "";
        date = ""; //doesn't reset
    }
}
<input type="date" name="date" id="date" onblur="validate_date();">

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If you need to use inline JS pass in the event to the function, then pick up the value from that. Then you can reset the value. This way you don't need an id on the input.

function validate_date(e) {
    var date = e.value;
    var date_object = new Date(date);
    var today = new Date();
    if (date_object <= today) {
      alert("Date cannot be today or the past!");
      e.value = '';
    }
}
<input type="date" onblur="validate_date(this);">

about 4 years ago · Juan Pablo Isaza Denunciar

0

when directly selecting an attribute of a DOM element, the variable becomes an independent entity.

By selecting the element instead will allow access to change its attributes.

function validate_date() {
  var date = document.getElementById("date");
  date.value = "";
}
<input type="date" name="date" id="date" onblur="validate_date();">

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda