2

I am working on a website for booking movie tickets. What should I set the min attribute to, to prevent past dates in the HTML5 datepicker? (I do not want to use PHP solution mentioned here.)

Is there a pure HTML5/Javascript solution for this?

Community
  • 1
  • 1
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138

2 Answers2

4

When the document loads have the date input disabled. Run an onload function that inserts today's date into the min field in the required format.

function onLoad() {
  var input = document.getElementById("dateField");
  var today = new Date();
  // Set month and day to string to add leading 0
  var day = new String(today.getDate());
  var mon = new String(today.getMonth()+1); //January is 0!
  var yr = today.getFullYear();

    if(day.length < 2) { day = "0" + day; }
    if(mon.length < 2) { mon = "0" + mon; }

    var date = new String( yr + '-' + mon + '-' + day );

  input.disabled = false; 
  input.setAttribute('min', date);
}

document.addEventListener('load', onLoad, false);

<body>
  <input id="dateField" type="date" disabled  />
</body>

Here it is in a fiddle: http://jsfiddle.net/tj9Xh/2/

atxpunkrock
  • 504
  • 8
  • 20
  • I updated the day to be a string as well. It's the 27th so I didn't think about single digit dates until after the fact. – atxpunkrock Jan 28 '14 at 04:46
1

try this:

<input id="dateField" type="date"/>


 var dt= new Date();
   var yyyy = dt.getFullYear().toString();
   var mm = (dt.getMonth()+1).toString(); // getMonth() is zero-based
   var dd  = dt.getDate().toString();
   var min = yyyy +'-'+ (mm[1]?mm:"0"+mm[0]) +'-'+ (dd[1]?dd:"0"+dd[0]); // padding
alert(min);
$('#dateField').prop('min',min);
Savaratkar
  • 1,974
  • 1
  • 24
  • 44