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

213
Views
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 answers
Answer question

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 Report

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 Report
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!