Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<input type="date> onchange fires too much

In Chrome at least, the <input type="date> onchange event fires on every keystroke that changes the date, which means if you are typing the year, for example, it will fire on every keystroke.

But, they aren't done changing the date yet! Seems like this is what oninput should be doing. I thought onchange was for the change as a whole. When I'm typing 0,1,1,5,1,9,8,7 (01/15/1987), that's not 8 changes, that's 1.

You could say, well, check the value onblur, but then my event will fire even if they are just tabbing through the field and it didn't change.

My handler is a generic ajax postback routine that doesn't / can't check the old vs new value.

Isn't there an event that fires only on a change (but when they are done changing)?

Maybe in onblur I could check the old value but I'm not sure how.

<input type="date" onchange="alert('changed')">
like image 553
toddmo Avatar asked Apr 28 '17 16:04

toddmo


2 Answers

You could use both handlers. Use the onChange to flag that the input has changed, and on the onBlur handler, check to see if it has been changed before doing whatever logic you need to do.

like image 84
Peter LaBanca Avatar answered Sep 29 '22 11:09

Peter LaBanca


<input type="date" id="mydate">

And Js:

let mydate=window.document.getElementById("mydate");
let olddate=mydate.value;
let isChanged = function(){
  if(mydate.value!== olddate){
    olddate=mydate.value;
    return true;
  };
  return false;
};
mydate.addEventListener("blur", function(){
  if(isChanged())
    alert("changed!");
});
like image 37
xale94 Avatar answered Sep 29 '22 12:09

xale94