HTML5 <input type=“date”> - onChange Event

Is possible to detect in event onChange for <input type=“date”>, when user using graphical calendar and arrows or using keybord number?

I am only interested in VanillaJS solutions.

Answers:

Answer

Something like this?

function handler(e){
  alert(e.target.value);
}
<input type="date" id="dt" onchange="handler(event);"/>

Answer

function elog(ev, object) {
    console.log(object.id + " - " + ev + ": " + object.value); 
}
<label for="dt1">Date not initially set: </label>
<input type="date" id="dt1" 
oninput="elog('input',this);return false;"
onchange="elog('change',this);return false;"
onblur="elog('blur',this);return false;"					 
onfocus="elog('focus',this);return false;"
onkeyup="elog('keyup-'+event.keyCode,this);return false;"
onkeypress="elog('keypress-'+event.keyCode,this);if(event.keyCode==13){this.onchange();return false;}" />

<label for="dt2">Date set to 1.12.1892 initially: </label>
<input type="date" id="dt2" 
value="1892-12-01"
oninput="elog('input',this);return false;"
onchange="elog('change',this);return false;"
onblur="elog('blur',this);return false;"					 
onfocus="elog('focus',this);return false;"
onkeyup="elog('keyup-'+event.keyCode,this);return false;"
onkeypress="elog('keypress-'+event.keyCode,this);if(event.keyCode==13){this.onchange();return false;}" />

I had a similar problem for determining whether or not the date picker was finished or closed by the user. Thus, I tested the change, blur, select and focus events, as shown in the code example (extension of antelove's example).

The change event only occurs if the date picker has a valid date set and the value changes. The input event behaves exactly the same. In some cases this can cause an undesired behaviour. When a valid date is already set (e.g. 01.12.1892) and the user starts typing a new 4 digit year, the change event will already be triggered after entering the first digit (e.g., 1994 => the change event appears after entering first digit '1'). If a backend is used, it might be undesirable to send every change to the server, but just the last and finally chosen date (or nothing, if the user aborts).

The blur event is fired when the input field looses focus. This also works for the datepicker shown on mobile safari (iOS). When the user presses "done/ok" the blur event is fired, which can be used to work with the chosen final date. Also here the change event fires, when ever the spin wheel stops and a one of the date components changed.

Interestingly the keypress event is not fired when a date component changes, however the keyup event is fired (even if not all date components are set). I have not found a way to extract the current set value of the incomplete date. Is there an option?

Not related to the question but useful: Adding a keypress handler to listen for key 13 (return/enter) is quite useful, when users enter a date on a website they can confirm the date via enter/return key, so no switch between keyboard/mouse is forced.

Summary: Yes, it is possible to see the changes of each of the dates components, if an initial date is set (or a complete date is set in the process) and the change event is processed. It is also possible to track the users actions in the date field when the date is complete. It is then possible to compare previous and current date value, which allows to find out where the 'cursor' currently resides. I guess that tracking the left/right/up/down keys will not work, since it is unknown which date component the user clicked.

Update for Android based on Alexanders comment: It seems that within the android browser, the datepicker element is still selected, i.e. in focus, when the datepicker is closed see example. In the example I clicked a date in the datepicker popup, afterwards I clicked on a region outside the datepicker. Afterwards I clicked "clear", and again outside the datepicker element. In all cases a click outside the datepicker (after the popup has closed) will cause the blur event to be fired. Since the change event is fired in all cases, maybe the best way to proceed is to implement a changed handler and a blur handler to catch both cases. But to be completely sure about the behaviour on post-wimp interaction styles (like touch), all browsers on mobile phones should be tested. I would not be surprised if implementations differ in various mobile browsers.

Answer

You could use two events onchange event but your field should be initialized first :

var date_input = document.getElementById('date_input');
date_input.valueAsDate = new Date();

date_input.onchange = function(){
   console.log(this.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id='date_input'>

Hope this helps.

Answer

Yes you can but kindly check support for the browser for date time support enter image description here

Check the bin for functional example!

JSBin

In case of Chrome the event will not be fired unless the whole date is input!

Answer

Format Date in YYYY-MM-DD

function getObject(object)
{
//  alert(object);
//  console.log(object);
  
  console.log(object.value); // result 2019-01-03
}
<input type="date" id="dt" onchange="getObject(this);"/>

Answer

Normally, onchange fires "when an alteration to the element's value is committed by the user". But for <input type='date'> fields, the major browser developers trigger onchange as soon as they detect a "valid" date in the field, even if you're still typing. They do this so that onchange will fire when a user selects a value from the (browser-specific) datapicker/calendar. There is basically no good way to differentiate between a date value entered by the datepicker and one manually typed in by the user.

This is a real problem if you use onchange to do something like submit the form. You'll get form submits with values you don't want, and as pointed out above, possibly bad data that might throw an exception (e.g. '0002-04-02' is a valid JS date but an invalid SQL date).

My solution is this:

  1. Bind your desired action to the onchange event
  2. On the onkeypress event:
    1. Remove the onchange binding
    2. Bind your desired action to the onblur event
    3. Add if (e.keyCode === 13) { doYourThing(); }

This means that your field correctly responds to onchange from the datepicker until the user starts to manually type a date. At that point, the onchange handler is removed (to prevent premature firing) and you instead bind onblur (for tabbing away) and keyCode === 13 (Enter key).

The only downside is that if a user starts to type a date, then changes their mind and uses the datapicker, onchange won't fire and your action won't happen until onblur or they press enter.

I know the OP requested pure JS, but here's my jQuery version.

$('input[type=date]').change(function () {
    this.form.submit();
});

$('input[type=date]').keypress(function (e) {
    $(this).off('change blur');

    $(this).blur(function () {
        this.form.submit();
    });

    if (e.keyCode === 13) {
        this.form.submit();
    }
});

EDIT: Unbind the onblur event before rebinding so you don't get multiple bound events.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.