I want to be able to set ...">

Setting default value for datetime-local

I use this html tag as a datetime collector:

<input type="datetime-local"> 

I want to be able to set the default value for part of the time , so if someone inserts a date and does not insert the time (leaves it as: -: -), then I can set it as 00:00:00, for example.

The problem is that I only know how to set a value, including date and time, and if someone inserts only a date without a time, when I cannot read this value and get an empty value.

Can this be overcome? or is there any other date and time collector that I could use for the described scenario?

+8
javascript jquery html html5 datetime
source share
1 answer

We cannot change the behavior of the browser against an element. So, this is the answer to the second question: if there is another solution for this scenario. I used two separate date and time fields that control a single datetime-local field.

Please note that the submitted date does not matter if the field is not completely filled. Therefore, I used the 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 in the time field (when it has a default value), but I noticed undefined behavior in google-chrome that if you change the time value set by mouse clicks, the change event is fired after mouseOut ! This does not affect the answer above.

Footnote 2: You can hide the result field inside the div display:none .

0
source share

All Articles