OVERVIEW:
I'm writing a jquery plugin which converts a textbox into a time entry box. Meaning it allows the user to enter time in HH:MM format. Part of this process is to insert a colon (:) at the right place. On keyup i check if the user has typed 2 numbers and if so append a colon to the entered value.
PROBLEM:
This approach works fine except when someone applies the plugin on the textbox but also wants to have a custom onchange handler.This onchange handler does not fire when the code updates the textbox value programmatically nor does it fire when the textbox loses focus.
MY UNDERSTANDING:
I'm guessing here, so please correct me if I'm wrong.
- Maybe the textbox has an internal
"_value"
(underscoring to differentiate from the public value attribute) field which holds the value in the textbox before the edit begins. When the focus leaves the texbox, the JS engine checks if the current value of the textbox matches the"_value"
of the textbox.If they are different, theonchange
event is fired. - Perhaps value changes using regular native keystrokes dont modify
"_value"
just the value, so theonchange
gets fired. But perhaps value changes made via JS modify both the value and the"_value"
and so the onchange event does not fire?
WORKAROUNDS:
The blur event fires as it has nothing to with the value. So I can explicitly fire the change event from the blur event.But I dont want to do this as it is a hack and breaks the semantics of blur and change.
RELATED LINKS:
I found several links on SO with the same question but no answer (IMHO) gives an elegant or correct solution. here are some of the ones I saw:
Javascript : onchange event does not fire when value is changed in onkeyup event
https://stackoverflow.com/questions/14410870/using-both-onchange-and-onkeyup-in-ie8
Javascript: "onchange" event does not work with "value" change in "text input" object
SIMPLIFIED CODE:
$(document).ready(function () {
$("input").keyup(function () {
this.value = '*' + this.value;
// this changes the value, but does not fire the onchange event
// and it also does not fire it when the textbox loses focus.
// blur fires though.
});
$("input").change(function () {
alert('in change');
});
$("input").blur(function () {
alert('in blur');
});
});
FIDDLE:
http://jsfiddle.net/sajjansarkar/vHgst/4/
BROWSERS TESTED: IE8,10 and Chrome. Works in FireFox(!!) (+1 Felix Kling)