Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda