Reputation: 183
I have a script that populates one of the fields in my form to today's date, however it only works when the input type is set to 'text'. PHP/SQL won't accept this value as the SQL datatype is set to 'date'. If anyone could explain how I might make this script compatible with the date input type I would greatly appreciate it.
HTML:
<div class="form-group">
<label class="control-label" for="flight_date">Date</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input id="flight_date" type="date" class="form-control" maxlength="10" name="flight_date">
</div>
</div>
jQuery:
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = day + "/" + month + "/" + year;
document.getElementById('flight_date').value = today;
Upvotes: 0
Views: 40
Reputation: 42044
The HTMLInputElement does not always expose the property "valueAsDate" in all browsers.
The valueAsDate.polyfill.js offers the possibility to extend this property on IE and FF.
The result is:
if(!("valueAsDate" in HTMLInputElement.prototype)){
Object.defineProperty(HTMLInputElement.prototype, "valueAsDate", {
get: function(){
var d = this.value.split(/\D/);
return new Date(d[0], --d[1], d[2]);
},
set: function(d){
var day = ("0" + d.getDate()).slice(-2),
month = ("0" + (d.getMonth() + 1)).slice(-2),
datestr = d.getFullYear()+"-"+month+"-"+day;
this.value = datestr;
}
});
}
var date = new Date();
document.getElementById('flight_date').valueAsDate = date;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="form-group">
<label class="control-label" for="flight_date">Date</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input id="flight_date" type="date" class="form-control" maxlength="10" name="flight_date">
</div>
</div>
Upvotes: 1
Reputation: 1081
To make input
accept the date format, you have to insert date string in yyyy-MM-dd format.
so change:
var today = day + "/" + month + "/" + year;
to:
var today = year+'-'+month+'-'+day;
Upvotes: 1
Reputation: 20740
Html <input type="date" />
supports date only in ISO format (yyyy-mm-dd) format. So you can do it like following.
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year +"-" + month + "-" + day;
document.getElementById('flight_date').value = today;
<input id="flight_date" type="date" class="form-control" maxlength="10" name="flight_date">
Upvotes: 2