I am using this html tag as a datetime picker:
<input type="datetime-local">
I want to be able to set a default value for the time part only so if someone inserts a date and doesn't insert the time (leaves it as --:--:--) then I will be able to set it as 00:00:00 for example.
The problem is I know only how to set the a value including both the date and time and if someone inserts only a date w/o the time I can't read that value and getting a blank value.
Is it possible to overcome that? or is there any other datetime picker I could use for the described scenario?
DD/MM/YYYY. MM/DD/YYYY.
The difference between the two is that the datetime-local input does not include the time zone. If the time zone is not important to your application, use datetime-local. Some browsers are still trying to catch up to the datetime input type.
We can not change the behavior of browser against an element. So this is an answer to the second question that if there is another solution for this scenario. I used two separate fields of date
and time
which control a single datetime-local
field.
Please note that the date
filed has no value unless the field is totally completed. So I used blur
event instead of keyup
or change
.
$(document).ready(function() {
var mydate, mytime, mystring;
$("#dateField").blur(function() {
if ($(this).val()) {
setResult();
}
})
$("#timeField").change(function() {
setResult()
})
})
function setResult() {
mydate = $("#dateField").val();
mytime = $("#timeField").val();
mystring = mydate + 'T' + mytime;
document.getElementById('resultField').value = mystring;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="dateField" type="date"><input id="timeField" type="time" value="18:30">
<br>
<strong>Result</strong>:
<br>
<input id="resultField" type="datetime-local">
Footnote 1:
The change
listener works on time
field (when has default value) but I noticed a vague behavior in google-chrome that if you change the value of time filed by mouse clicks, the change event is triggered after mouseOut
! This has no effect on the answer above.
Footnote 2:
You can hide the result field inside a display:none
div.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With