Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default time value for datetime-local

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?

like image 301
Josh Avatar asked Aug 15 '14 09:08

Josh


People also ask

What is the format of datetime local?

DD/MM/YYYY. MM/DD/YYYY.

What is the difference between datetime and datetime local?

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.


1 Answers

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.

like image 188
Ali Sheikhpour Avatar answered Oct 16 '22 22:10

Ali Sheikhpour