<input type="date"> - jQuery catch event clear date

Viewed 3867

I don't know how to catch the event of clearing the date, when deleting the date by clicking the x. The click event is not useful, because i get the change event.

HTML:

Date Field with clear x

i want to catch the event when clicking the x (see pic). Any Hints?

Using jQuery v3.2.1 and Bootstrap v3

2 Answers

You can just listen for the change event. This script should work with or without jQuery and will write to the console when a value is set and when the clear button is clicked:

var input = document.getElementsByTagName('input')[0];

input.addEventListener('change', function(e) {
  if (!input.value)
    console.log('clear!');

  else
    console.log('value', input.value);
});
<input type="date" />

Thank You Keith, thats was a good inpiration for my solution.

I'm used jquery for the project, so i needed a solution in jquery.

this js solution solves one problem, but another problem was: if loading the page and deleting the date value by clicking the clear button ("x"), the change event didn't recognized it. the solution:

$('.date-input')
    .click(function(e) {
         $(this).focus();
    }
    .change(function(e) {
         var myValue = $(this);
         if (!myValue.val()) {
            // do something when cleared
         } else {
            // do something on changed date
         }
    });

HTML:

<input type="date" class="date-input" />
Related