45

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.

3
  • So the question basically is whether onchange works properly? Why not just try it out? (If you mean whether onchange fires every time the user changes the position in the calendar but doesn't finish editing - my guess would be probably not.)
    – Pekka
    Nov 23, 2016 at 11:08
  • 2
    The funny thing is that the event is only triggered when the date is valid. When you use the keyboard, you're constructing the date, piece by piece. Once the date is valid, the events will start firing. Nov 23, 2016 at 11:23
  • 1
    you are right, but date 0002 is valid. So when someone writing new year(2016), and press first number 2, component is rerender and input date has new value 0002. Someone want press second number (0), component is again rerender and has again new value 0000. I thought that it is a simple way to detect in event object when date is change using keyboard. I solved this by doing a custom validation in eventHandler Nov 23, 2016 at 11:34

8 Answers 8

51

Something like this?

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

1
  • This only catches the first valid date entered. No changes. Dec 13, 2022 at 2:10
23

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.

4
  • 1
    Any idea how we can force the 'blur' event on android browsers when the datepicker is closed? Sep 18, 2019 at 12:23
  • @AlexanderDerck I tested it within an AVD with Android 8 and Android Browser and it seems the blur event is not fired, because the datepicker is still on focus after the popup closes. Probably related to the touch interaction style on mobile browsers. I updated the post accordingly.
    – holsteto
    Sep 29, 2019 at 15:59
  • I solved it by checking if the user agent is android related and trigger a blur event on the input when a change event is fired. Oct 1, 2019 at 17:02
  • Extract the partial value while editing using the keyup event, this.value used like onkeyup="console.log('keyup-' + this.value);return false;" works in Chrome. Anyone else's experience? Feb 11, 2021 at 11:41
18

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.

3
  • Is there a safe way to reinstall the onchange handler when the user switches back to a datepicker? Oct 14, 2021 at 13:55
  • 1
    Not that I know of. The datepickers are all browser-specific (and some are quite different) and I don't think there is any kind of "onSelect" or "onOpen" event that you could bind to. They aren't even DOM elements. We can detect typing in the input field (onKeypress) since the field is a DOM element. Oct 20, 2021 at 3:53
  • Posted an answer you might want to review.
    – Terry
    Sep 28, 2022 at 16:35
4

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.

8
  • This is a patch.. What if initial value is not set(Quite common scenario!)
    – Rayon
    Nov 23, 2016 at 11:44
  • You can't detect the change until you enter a valide date, so if initial value is not set you should just set a valid date (using keyboard or graphycal component) and it will be detected. Nov 23, 2016 at 11:45
  • 1
    Yeah! I have been in similar situation in past... Using multiple events(keyup/onchange/oninput/click) together will do!
    – Rayon
    Nov 23, 2016 at 11:48
  • I've tried that before, first it will fire the event multiple time when you make one chnage, second you will never get the value until it's a valid date. (jsfiddle.net/z_acharki/jnwrc5ay/238) Nov 23, 2016 at 11:53
  • Second point is true and quite logical, why would care about invoking handlers multiple times ? Yes! it is a patch, not so perfect solution...
    – Rayon
    Nov 23, 2016 at 11:54
2

Based on @neil-laslett answer I expanded just a bit to 're-install' the change event when he mentioned if they started typing then changed mind...

So flow:

  1. Create action to do calculation if the stored input value is different than date input value.
  2. Bind action to change
  3. Bind to keypress
    • When typing, remove change event and bind action to blur
    • If keyCode=13 (enter), fire action
  4. Bind to click event
  5. Remove blur and change, re-add change event
// assumptions: application.state.inputs is just a variable holding last known input values.
// dateChangeAsync: I needed to be async/await, but obviously just remove that if your action doesn't do anything asynchronous.
// name/input: Scoped variable holding appropriate references.  Could have used input.value instead of application.getInputValue(name) probably, but is part of a framework that supports all types of inputs.

const dateChangeAsync = async () => {
    // Since we might be triggered on a blur vs a change, a blur would happen every time
    // they 'tab' through an input or if they type a value and change it back to same 
    // value before tabbing out (normal inputs automatically handle this and doesn't 
    // trigger change event)
    if (application.state.inputs[name] != application.getInputValue(name)) {
        application.state.inputs[name] = application.getInputValue(name);
        await inputEventAsync(true);                
    }
};

input.addEventListener("change", dateChangeAsync);

input.addEventListener("keypress", async e => {
    input.removeEventListener("change", dateChangeAsync);
    input.addEventListener("blur", dateChangeAsync);

    if (e.keyCode == 13) {
        await dateChangeAsync();
    }
});

input.addEventListener("click", e => {
    input.removeEventListener("blur", dateChangeAsync);
    input.removeEventListener("change", dateChangeAsync);
    input.addEventListener("change", dateChangeAsync);
});
1

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);"/>

0

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!

1
  • I doubt that the OP wants to target those old browsers (2011. - 2012.)
    – Vucko
    Nov 23, 2016 at 11:17
0

Not the most fool-proof solution, but probably the simplest:

<input type="date" onchange="if (!this.value.startsWith('0')) yourFunction();">

Props to @Neil Laslett for his explanation of the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.