1

There is <input type=date> field in my html page. And I am trying to make a function in javascript that will set today's date in that field if some date greater than today has been chosen. Actually, I would like to restrict maximum date to today's date. Here is code in jsfiddle. What am I doing wrong?

HTML:

<div class="entry">
    <label for="startDate">Start date:</label>
    <input id="startDate" name="startDate" type="date" oninput="validDate(startDate)">
</div>

Javascript:

function validDate(date) {
    todayDate = getTodaysDate();
    if (date > todayDate)
        document.searchForm["date"].value = todayDate;
}

function getTodaysDate(){
    date = new Date();
    day = date.getDate();
    month = date.getMonth() + 1;
    year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    today = year + "-" + month + "-" + day; 

    return today;
}
kapa
  • 77,694
  • 21
  • 158
  • 175
Vladimir
  • 1,624
  • 7
  • 25
  • 56

2 Answers2

3

You can set the max attribute to restrict it to todays date:

document.getElementById('startDate').setAttribute('max', getTodaysDate());

See http://jsfiddle.net/4jCT6/1/

sroes
  • 14,663
  • 1
  • 53
  • 72
1

Here's an updated fiddle which works for me (in Chrome/Windows, at least):

http://jsfiddle.net/nFHLn/4/

JavaScript:

function validDate(date, theInput) {
    var date = document.getElementById("startDate").value;
    todayDate = getTodaysDate();
    if (date > todayDate)
        theInput.value = todayDate;
}

function getTodaysDate(){
    date = new Date();
    day = date.getDate();
    month = date.getMonth() + 1;
    year = date.getFullYear();

    if (month < 10) month = "0" + month;
    if (day < 10) day = "0" + day;

    today = year + "-" + month + "-" + day; 

    return today;
}

HTML:

<div class="entry">
    <label for="startDate">Start date:</label>
    <input id="startDate" name="startDate" type="date" oninput="validDate(this.value, this)">
</div>
MassivePenguin
  • 3,701
  • 4
  • 24
  • 46
  • It does work, yes. But that `validDate(date)` function looks little odd to me. You are not calling function with any argument. And I wanted to use this function for more than one date field on the form, not only `startDate`. – Vladimir Jan 14 '14 at 11:16
  • You're right; that was an error on my part. I've updated my answer (and Fiddle) to make the code more portable; you should be able to use it on different date inputs now. – MassivePenguin Jan 14 '14 at 12:21