Martin Barker Martin Barker - 1 year ago 59
jQuery Question

jQuery .val not updating DOM on input date

So i seem to have found a problem im not sure if this is jQuery bug or it's just not possible but if any one has managed this could they tell me how.

I have a Date picker and i don't want to allow users to select dates in the past.

var d = new Date($(this).val());
var nowDate = new Date();
var nowDateParse = ""+
(nowDate.getMonth()+1 < 10? "0"+(nowDate.getMonth()+1): (nowDate.getMonth()+1))+
(nowDate.getDate()+1 < 10? "0"+(nowDate.getDate()+1): (nowDate.getDate()+1));
var selDate = ""+
(d.getMonth()+1 < 10? "0"+(d.getMonth()+1): (d.getMonth()+1))+
(d.getDate()+1 < 10? "0"+(d.getDate()+1): (d.getDate()+1));
if(parseInt(nowDateParse) > parseInt(selDate)){
alert("You can only select dates in the future!");
$("#searchDate").attr("value", ""+
(nowDate.getMonth()+1 < 10? "0"+(nowDate.getMonth()+1): (nowDate.getMonth()+1))+"-"+
(nowDate.getDate()+1 < 10? "0"+(nowDate.getDate()+1): (nowDate.getDate()+1))
return false;

as you can see i have tired
as well as
but both seem to cause the same problem.

So Date starts on the current date: 27/06/2016 (UK format for: 2016-06-27)

if the user selects a date before that E.G 26/06/2016 (UK format for: 2016-06-26)

it shows the alert but fails to change the date back to today's date.

I'm not against using Standard Javascript with out jQuery calls if thats what is needed.


As a note this code looks quite complex due to the fact it's doing a date comparison and not a datetime comparison as Javascript's
object is a datetime not just a date

Answer Source

Add this after the control of the date validity:

    var dToday = new Date();
    var day = ("0" + dToday.getDate()).slice(-2);
    var month = ("0" + (dToday.getMonth()+1)).slice(-2);
    today = dToday.getFullYear() + "-" + month + "-" + day;
<script src=""></script>
<input type="date" id="searchDate">